引入maven
<!--图片验证码--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> <exclusions> <exclusion> <artifactId>javax.servlet-api</artifactId> <groupId>javax.servlet</groupId> </exclusion> </exclusions> </dependency>
验证码配置类
KaptchaConfig.java
package com.test.cms.kaptcha; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; /** * 验证码配置 */ @Configuration public class KaptchaConfig { @Bean(name = "captchaProducer") public DefaultKaptcha getKaptchaBean() { Properties properties = new Properties(); //图片边框 properties.setProperty("kaptcha.border", "no"); //文本集合,验证码值从此集合中获取 properties.setProperty("kaptcha.textproducer.char.string", "ABCDEGHJKLMNRSTUWXY23456789"); //字体颜色 properties.setProperty("kaptcha.textproducer.font.color", "0,84,144"); //干扰颜色 properties.setProperty("kaptcha.noise.color", "0,84,144"); //字体大小 properties.setProperty("kaptcha.textproducer.font.size", "30"); //背景颜色渐变,开始颜色 properties.setProperty("kaptcha.background.clear.from", "247,255,234"); //背景颜色渐变,结束颜色 properties.setProperty("kaptcha.background.clear.to", "247,255,234"); //图片宽 properties.setProperty("kaptcha.image.width", "125"); //图片高 properties.setProperty("kaptcha.image.height", "35"); properties.setProperty("kaptcha.session.key", "code"); //验证码长度 properties.setProperty("kaptcha.textproducer.char.length", "4"); //字体 properties.setProperty("kaptcha.textproducer.font.names", "Arial, Courier"); Config config = new Config(properties); DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
控制器类
KaptchaController.java
package com.test.cms.kaptcha; import com.google.code.kaptcha.Producer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import sun.misc.BASE64Encoder; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; @RestController public class KaptchaController { /** * 加载图形验证码 */ @GetMapping("/kaptcha") public String getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setDateHeader("Expires", 0); // 设置浏览器渲染不做本地缓存 response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Content-Security-Policy", "none"); // 设置浏览器渲染不读取浏览器缓存 response.setHeader("Pragma", "no-cache"); String originHeader = request.getHeader("Origin"); // 这个限定来自自身服务端域名 /*if (originHeader != null && (originHeader.contains(request.getServerName()))) { response.setHeader("Access-Control-Allow-Origin", originHeader); } else { response.setHeader("Access-Control-Allow-Origin", request.getServerName()); }*/ // 设置浏览器渲染图片类型 response.setContentType("image/jpeg"); // 生成验证码内容 String capText = captchaProducer.createText(); String sessionId = request.getSession().getId(); System.out.println(sessionId + "," + capText); /** *这里将sessionId作为key存入redis中,用于后面的验证码验证,可以设置失效时间 * springboot整合redis可以参考 https://www.cnblogs.com/pxblog/p/12980634.html */ //redisService.set(Constants.KAPTCHA_SESSION_KEY+sessionId, capText); //生成图片 BufferedImage bi = captchaProducer.createImage(capText); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(bi, "jpg", outputStream); Map<String, Object> map = new HashMap<String, Object>(2); //转为base64 String img=imageToBase64ByByte(outputStream.toByteArray()); map.put("img", img); //sessionId 主要用于验证验证码使用 map.put("sessionId", sessionId); try { outputStream.flush(); }finally { outputStream.close(); } //这里将map返回到前台,此处简单demo return img+","+sessionId; } public static String imageToBase64ByByte(byte[] data) { BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); } /** * 验证验证码是否正确 * @param code 前台填写的验证码 * @param sessionId 生成验证码时返回的sessionId * @return */ @GetMapping("/valid") public Boolean valid(String code,String sessionId) { String verifyCode ="这里从redis中取出原本的验证码进行判断:redisService.get(Constants.KAPTCHA_SESSION_KEY+sessionId)"; System.out.println(verifyCode); return verifyCode.equalsIgnoreCase(code); } @Autowired private Producer captchaProducer; }
页面调用
<div class="letter pointer" id="getCapatchImg"><img id="capatchImg" onclick="genCapatch()" /></div>
// 图形验证码
var sessionId=""; $(function () { $("#getCapatchImg").on("click", function (event) { genCapatch(); }); }); function genCapatch() { $.ajax({ url: "/kaptcha", data: {}, success: function (result) { document.getElementById('capatchImg').src = "data:image/png;base64," + result.data.img; sessionId=result.data.sessionId } }); }