Kaptcha 是一个可高度配置的实用验证码生成工具,可自由配置的选项如:
验证码的字体
验证码字体的大小
验证码字体的字体颜色
验证码内容的范围(数字,字母,中文汉字!)
验证码图片的大小,边框,边框粗细,边框颜色
验证码的干扰线
验证码的样式(鱼眼样式、3D、普通模糊、...)
Maven引入kaptcha:
<!-- google验证码 --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
首先是通过编码指定验证码生成的一些规则
package com.example.demo.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() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "yes"); properties.setProperty("kaptcha.border.color", "105,179,90"); properties.setProperty("kaptcha.textproducer.font.color", "blue"); properties.setProperty("kaptcha.image.width", "160"); properties.setProperty("kaptcha.image.height", "60"); properties.setProperty("kaptcha.textproducer.font.size", "28"); properties.setProperty("kaptcha.session.key", "kaptchaCode"); properties.setProperty("kaptcha.textproducer.char.spac", "35"); properties.setProperty("kaptcha.textproducer.char.length", "5"); properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier"); properties.setProperty("kaptcha.noise.color", "white"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } @Bean(name = "captchaProducerMath") public DefaultKaptcha getKaptchaBeanMath() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); properties.setProperty("kaptcha.border", "yes"); properties.setProperty("kaptcha.border.color", "105,179,90"); properties.setProperty("kaptcha.textproducer.font.color", "blue"); properties.setProperty("kaptcha.image.width", "100"); properties.setProperty("kaptcha.image.height", "30"); properties.setProperty("kaptcha.textproducer.font.size", "30"); properties.setProperty("kaptcha.session.key", "kaptchaCodeMath"); properties.setProperty("kaptcha.textproducer.impl", "com.lhf.springboot.support.KaptchaTextCreator"); properties.setProperty("kaptcha.textproducer.char.spac", "5"); properties.setProperty("kaptcha.textproducer.char.length", "6"); properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier"); properties.setProperty("kaptcha.noise.color", "white"); properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise"); properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } }
参数解释如下表格
编写一个数算类生成公用类
package com.example.demo.kaptcha; import com.google.code.kaptcha.text.impl.DefaultTextCreator; import java.util.Random; public class KaptchaTextCreator extends DefaultTextCreator { private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(","); @Override public String getText() { Integer result = 0; Random random = new Random(); int x = random.nextInt(10); int y = random.nextInt(10); StringBuilder suChinese = new StringBuilder(); int randomoperands = (int) Math.round(Math.random() * 2); if (randomoperands == 0) { result = x * y; suChinese.append(CNUMBERS[x]); suChinese.append("*"); suChinese.append(CNUMBERS[y]); } else if (randomoperands == 1) { if (!(x == 0) && y % x == 0) { result = y / x; suChinese.append(CNUMBERS[y]); suChinese.append("/"); suChinese.append(CNUMBERS[x]); } else { result = x + y; suChinese.append(CNUMBERS[x]); suChinese.append("+"); suChinese.append(CNUMBERS[y]); } } else if (randomoperands == 2) { if (x >= y) { result = x - y; suChinese.append(CNUMBERS[x]); suChinese.append("-"); suChinese.append(CNUMBERS[y]); } else { result = y - x; suChinese.append(CNUMBERS[y]); suChinese.append("-"); suChinese.append(CNUMBERS[x]); } } else { result = x + y; suChinese.append(CNUMBERS[x]); suChinese.append("+"); suChinese.append(CNUMBERS[y]); } suChinese.append("=?@" + result); return suChinese.toString(); } }
编写接收验证码请求的Controller然后输出图片文件流
package com.example.demo.kaptcha; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.awt.image.BufferedImage; import java.io.IOException; /** * 验证码生成控制器 */ @Controller @Api(value = "验证码生成") @RequestMapping("/captcha") public class CaptchaController { @Autowired private Producer captchaProducer; @Autowired private Producer captchaProducerMath; /** * 跳转到验证码页面 */ @RequestMapping("/home") public String home(Model model) { return "img"; } /** * 验证码生成 */ @ApiOperation(value = "生成谷歌验证码") @GetMapping(value = "/captchaImage") public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) { ServletOutputStream out = null; try { HttpSession session = request.getSession(); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String type = request.getParameter("type"); String capStr = null; String code = null; // 这个就是文本框要输入的结果,为数算时这个就是计算后的结果 BufferedImage bi = null; // 验证码为算数 8*9 类型 if ("math".equals(type)) { String capText = new KaptchaTextCreator().getText(); capStr = capText.substring(0, capText.lastIndexOf("@")); code = capText.substring(capText.lastIndexOf("@") + 1); bi = captchaProducerMath.createImage(capStr); } else if ("char".equals(type)) { // 验证码为 abcd类型 capStr = code = captchaProducer.createText(); bi = captchaProducer.createImage(capStr); } session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code); out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); System.out.println("bi = " + bi); System.out.println("out =" + out); out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } }
页面代码如下,注意引入了百度公用JS:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script> </head> <body> <form th:action="@{/home}" method="post" id="loginForm"> <div> <div style="width:86%;padding-left:8%;padding-top: 40px;"> <div style="float: left;width:100px; height: 40px;"> <i><img style="height:40px;" id="codeImg1" alt="点击更换" title="点击更换" src="captcha/captchaImage?type=char" /></i> </div> <br /> <br /> <br /> <div style="float: left;width:100px; height: 40px;"> <i><img style="height:40px;" id="codeImg2" alt="点击更换" title="点击更换" src="captcha/captchaImage?type=math" /></i> </div> </div> </div> </form> <!-- 软键盘控件end --> <script type="text/javascript"> var message = "[[${message}]]"; if ("" != message) { layer.msg(message, { time : 3000 }) } $('#codeImg1').click(function() { var url = "captcha/captchaImage?type=char&s=" + Math.random(); $("#codeImg1").attr("src", url); }); $('#codeImg2').click(function() { var url = "captcha/captchaImage?type=math&s=" + Math.random(); $("#codeImg2").attr("src", url); }); function severCheck() { $("#loginForm").submit(); } //session获取iframe处理 $(function() { //判断一下当前是不是做顶层,如果不是,则做一下顶层页面重定向 if (window != top) { top.location.href = location.href; } }); </script> </body> </html>
访问http://localhost:8080/home 会跳转到响应页面,这个页面会展示验证码。
推荐您阅读更多有关于“ 验证码 kaptcha springboot google ”的文章
Java小强
未曾清贫难成人,不经打击老天真。
自古英雄出炼狱,从来富贵入凡尘。
发表评论: