验证码笔记
需要的两个jar包
一、导入依赖
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
二、前端生成验证码
<img src="${pageContext.request.contextPath}/captcha" style="width:85px" id="cap"/>
<input type="text" placeholder="验证码" id="captcha" name="captcha">
$(function(){
loadCaptcha();
});
$("#cap").click(function(){
loadCaptcha();
});
function loadCaptcha(){
path = $("img").attr("src")+"?"+new Date().getTime();
$("img").attr("src",path);
}
$("#entry_btn").click(function(){
var username = $("input[name='username']").val();
var password = $("input[name='password']").val();
var captcha = $("input[name='captcha']").val();
$.ajax({
type:"post",
url:"login.do",
data:{
username:username,
password:password,
captcha:captcha
},
dataType:"json",
success:function(result){
if(result.status == true){
window.location.href = "pages/index.jsp";
}else{
loadCaptcha();
alert(result.message);
}
}
});
});
三、web.xml配置验证码,将验证码存入session
<servlet>
<servlet-name>cap</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.char.length</param-name>
<param-value>4</param-value>
</init-param>
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</param-value>
</init-param>
<init-param>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>211,229,237</param-value>
</init-param>
<init-param>
<param-name>kaptcha.session.key</param-name>
<param-value>captcha</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>cap</servlet-name>
<url-pattern>/captcha</url-pattern>
</servlet-mapping>
四、后台认证验证码
String captcha = req.getParamater("captcha");
HttpSession session = req.getSession();
String realCap = (String)session.getAttribute("captcha");
if(realCap.equalsIgnoreCase(captcha)) {
成功了
}else {
失败了
}