一.配置kaptcha的jar包
pom.xml配置:
<-- 目前只有2.3.2版本--> <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha --> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
二.kaptcha样式配置
web.xml:配置kaptcha的servlet及部分样式
<servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- 定义验证码样式 --> <!-- 是否有边框 --> <init-param> <param-name>kaptcha.border</param-name> <!-- 没有边框 no --> <param-value>no</param-value> </init-param> <!-- 字体颜色 --> <init-param> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>red</param-value> </init-param> <!-- 图片宽度 --> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>135</param-value> </init-param> <!-- 使用哪些字符生成验证码 --> <init-param> <param-name>kaptcha.textProducer.char.string</param-name> <param-value>ACDEFHKPRSTWX345679</param-value> </init-param> <!-- 图片高度 --> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <!-- 字体大小 --> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>43</param-value> </init-param> <!-- 干扰线的颜色 --> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <!-- 验证码字符个数 --> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <!-- 字体 --> <init-param> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Aria</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <url-pattern>/Kaptcha</url-pattern> </servlet-mapping>
kaptcha详细参数:
三.后端验证
从前端接收验证码并验证是否正确:
import javax.servlet.http.HttpServletRequest; public class CodeUtil { public static boolean checkVerifyCode(HttpServletRequest request) { String verifyCodeExpected = (String) request.getSession() .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String verifyCodeActual = HttpServletRequestUtil.getString(request, "verifyCodeActual"); if (verifyCodeActual == null || !verifyCodeActual.equals(verifyCodeExpected)) { return false; } return true; } }
· 前端部分js代码:
..... <!-- 获取输入框验证码--> var verifyCodeActual=$('#j_captcha').val(); if(!verifyCodeActual){ $.toast("请输出验证码"); return; } <!--通过ajax异步提交--> formData.append('verifyCodeActual',verifyCodeActual); $ajax({ url:registerShopUrl, type:'POST', data:formData, contentType:false, processData:false, cacche:false, success:function(data){ if(data.success){ $.toast("提交成功"); } else{ $.toast("提交失败:"+data.errMsg); } $('#captcha_img').click(); } })