SpringMVC+kaptcha实现图形验证码
基础准备
maven
在pom.xml中引入依赖即可。
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
配置
在applicationContext中写入配置
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<prop key="kaptcha.border">yes</prop>
<prop key="kaptcha.border.color">105,179,90</prop>
<prop key="kaptcha.textproducer.font.color">blue</prop>
<prop key="kaptcha.image.width">125</prop>
<prop key="kaptcha.image.height">45</prop>
<prop key="kaptcha.textproducer.font.size">45</prop>
<prop key="kaptcha.session.key">code</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
代码编写
后端
声明一个Controller用来处理请求,并返回图片。同时将验证码存在Session中,用于后期验证。
@Controller
@RequestMapping("/kaptcha")
public class CaptchaController {
Producer captchaProducer = null;
@Autowired
public void setCaptchaProducer(Producer captchaProducer) {
this.captchaProducer = captchaProducer;
}
@RequestMapping("/doGet")
public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setDateHeader("Expires", 0);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
// return a jpeg
response.setContentType("image/jpeg");
// create the text for the image
String capText = captchaProducer.createText();
// store the text in the session
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
System.out.println("Captchca:"+request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
return null;
}
}
前端
主页这里为了不让验证码图片被缓存,需要在请求后边加入随机数。
function refreshCaptcha(){
var ran = Math.floor(Math.random() * 100)
$('#captcha1').attr('src','/webRoot/kaptcha/doGet?' + ran);
}
验证码认证
将用户输入的字符串与Session中保存的验证码进行比较即可
@ResponseBody
@RequestMapping(value="doLogin", method = RequestMethod.POST)
public ResultInfo doLogin(HttpServletRequest request, HttpServletResponse response){
ResultInfo result = new ResultInfo();
String captcha = request.getParameter("captcha");
if(!captcha.equals(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY))){
result.setStateId(-1);
result.setErrorMsg("验证码不正确");
return result;
}
/*其它的登录代码*/
return result;
}
还没有评论,来说两句吧...