1、引入jar包
<!-- 验证码 https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
2、配置web.xml
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!--(样式) 是否有边框 -->
<init-param>
<param-name>kaptcha.border</param-name>
<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.textproducer.char.string</param-name>
<param-value>QWERTYUIOPLKJHGFDSAMNBVCXZ123456789</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.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>Arial</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/Kaptcha</url-pattern>
</servlet-mapping>
3、页面标签定义
<!-- 验证码 避免重复提交 (kaptcha控件)-->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">验证码:</div>
<input type="text" id="j_kaptcha" placeholder="验证码">
<div class="item-input">
<img type="text" id="kaptchaImg" alt="点击更换" title="点击更换" onclick="changeVerifyCode(this)" src="../Kaptcha">
<!-- src="../Kaptcha" src指定web中配置的名字 即:Kaptcha -->
</div>
</div>
</div>
</li>
4、JS方法 (更换验证码)
function changeVerifyCode(img){
img.src='../Kaptcha?'+Math.floor(Math.random() * 100);
}
5、后台验证
public static boolean CheckVerifyCode(HttpServletRequest request){
String verifyCodeExpected=(String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
String code=HttpServletRequestUtil.getString(request, "code");
if(code == null || !code.equals(verifyCodeExpected) ){
return false;
}
return true;
}