作者:安小辰 | 来源:互联网 | 2023-12-13 13:58
一.配置kaptcha的jar包
pom.xml配置:
<-- 目前只有2.3.2版本-->
<dependency>
<groupId>com.github.pengglegroupId>
<artifactId>kaptchaartifactId>
<version>2.3.2version>
dependency>
二.kaptcha样式配置
web.xml:配置kaptcha的servlet及部分样式
<servlet>
<servlet-name>Kaptchaservlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServletservlet-class>
<init-param>
<param-name>kaptcha.borderparam-name>
<param-value>noparam-value>
init-param>
<init-param>
<param-name>kaptcha.textproducer.font.colorparam-name>
<param-value>redparam-value>
init-param>
<init-param>
<param-name>kaptcha.image.widthparam-name>
<param-value>135param-value>
init-param>
<init-param>
<param-name>kaptcha.textProducer.char.stringparam-name>
<param-value>ACDEFHKPRSTWX345679param-value>
init-param>
<init-param>
<param-name>kaptcha.image.heightparam-name>
<param-value>50param-value>
init-param>
<init-param>
<param-name>kaptcha.textproducer.font.sizeparam-name>
<param-value>43param-value>
init-param>
<init-param>
<param-name>kaptcha.noise.colorparam-name>
<param-value>blackparam-value>
init-param>
<init-param>
<param-name>kaptcha.textproducer.char.lengthparam-name>
<param-value>4param-value>
init-param>
<init-param>
<param-name>kaptcha.textproducer.font.namesparam-name>
<param-value>Ariaparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>Kaptchaservlet-name>
<url-pattern>/Kaptchaurl-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;
}
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();
}
})