maven工程,在pom文件中加入依赖包。
<!-- 验证码类 kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
然后在web.xml中,配置kaptcha的使用:
<!-- 验证码 -->
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>kaptcha.obscurificator.impl</param-name>
<param-value>com.google.code.kaptcha.impl.FishEyeGimpy</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/kaptcha.jpg</url-pattern>
</servlet-mapping>
配置验证码的样式,主要的样式可以通过init-param的装载属性,然后在页面上的img标签上面即可直接使用src
为kaptcha.jpg直接调用图片。
验证 验证码是否正确
package com.xxx.util;
import javax.servlet.http.HttpServletRequest;
import com.google.code.kaptcha.Constants;
public class VerifyCaptcha {
public static boolean verify(HttpServletRequest request) {
// 从session中取出servlet生成的验证码text值
String expected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
// 获取用户页面输入的验证码
String received = request.getParameter("kaptcha");
return received != null && received.equalsIgnoreCase(expected);
}
}
kaptcha已经帮我们把验证码的值写入了session中,我们可以通过,获取页面穿过来的参数,自定义判断是否正确。其session的名称是Constants.KAPTCHA_SESSION_KEY