說明:驗證碼,是登錄流程中必不可少的一環,一般企業級的系統,使用都是專門制作驗證碼、審核校驗的第三方SDK(如極驗)。本文介紹,使用谷歌提供的Kaptcha技術,制作一個簡單的驗證碼。
本文參考(http://t.csdn.cn/55Ip2),基本是根據這篇文章自己手動實現了一遍。
后端代碼
創建一個SpringBoot項目,依賴如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>kaptcha_essay</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><!--Springboot項目--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version><relativePath/></parent><dependencies><!--web依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--kaptcha依賴--><dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency></dependencies></project>
創建一個Kaptcha配置類,用于設置驗證碼的尺寸、樣式等,注意不要漏掉@Component注解
如下:
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;import java.util.Properties;@Component
public class KaptchConfig {@Beanpublic DefaultKaptcha getDefaultKaptcha() {// 創建驗證碼工具com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();// 驗證碼配置Properties properties = new Properties();// 圖片邊框properties.setProperty("kaptcha.border", "no");// 邊框顏色properties.setProperty("kaptcha.border.color", "black");//邊框厚度properties.setProperty("kaptcha.border.thickness", "1");// 圖片寬properties.setProperty("kaptcha.image.width", "120");// 圖片高properties.setProperty("kaptcha.image.height", "60");//圖片實現類properties.setProperty("kaptcha.producer.impl", "com.google.code.kaptcha.impl.DefaultKaptcha");//文本實現類properties.setProperty("kaptcha.textproducer.impl", "com.google.code.kaptcha.text.impl.DefaultTextCreator");//文本集合,驗證碼值從此集合中獲取properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");//驗證碼長度properties.setProperty("kaptcha.textproducer.char.length", "4");//字體properties.setProperty("kaptcha.textproducer.font.names", "宋體");//字體顏色properties.setProperty("kaptcha.textproducer.font.color", "black");//文字間隔properties.setProperty("kaptcha.textproducer.char.space", "4");//干擾實現類properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.DefaultNoise");//干擾顏色properties.setProperty("kaptcha.noise.color", "blue");//干擾圖片樣式properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");//背景實現類properties.setProperty("kaptcha.background.impl", "com.google.code.kaptcha.impl.DefaultBackground");//背景顏色漸變,結束顏色properties.setProperty("kaptcha.background.clear.to", "white");//文字渲染器properties.setProperty("kaptcha.word.impl", "com.google.code.kaptcha.text.impl.DefaultWordRenderer");// 創建驗證碼配置實例Config config = new Config(properties);// 驗證碼工具defaultKaptcha.setConfig(config);return defaultKaptcha;}
}
創建一個controller層類,用于生成驗證碼并返回
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;@RestController
@CrossOrigin
@RequestMapping("/code")
public class KaptchController {@ResourceDefaultKaptcha defaultKaptcha;/*** 生成驗證碼*/@GetMappingpublic Map code() throws IOException {// 生成文字驗證碼String text = defaultKaptcha.createText();System.out.println("文字驗證碼為" + text);ByteArrayOutputStream out = new ByteArrayOutputStream();// 生成圖片驗證碼BufferedImage image = defaultKaptcha.createImage(text);ImageIO.write(image, "jpg", out);// 對字節組Base64編碼return Map.of("data", Base64.getEncoder().encodeToString(out.toByteArray()));}
}
@CrossOrigin注解,用于解決跨域問題,待會兒前端會發送異步請求,獲取驗證碼;
前端代碼
創建一個前端頁面,使用axios向后端發送獲取驗證碼的請求;
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>獲取驗證碼</title><script src="js/axios-0.18.0.js"></script></head><body><input type="button" value="獲取驗證碼" onclick="get()"><img id="pic" />
</body>
<script>function get() {// 異步交互ajaxaxios.get("http://localhost:8080/code") // 發請求給服務器.then(resp => {// 接收響應回來的數據console.log(resp.data);document.getElementById("pic").src = 'data:image/jpeg;base64,' + resp.data.data;})}
</script></html>
啟動&測試
啟動代碼,打開前端頁面,點擊獲取驗證碼,查看結果,如下:
控制臺輸出驗證碼,這個驗證碼在實際開發中可存入Redis中;
可以前端查看返回的內容;
這段地址加上data:image/jpeg;base64,
就是驗證碼的圖片地址;