Spring MVC中使用Google kaptcha验证码的方法详解
前言
众所周知验证码是抵抗批量操作和恶意登录最有效的方式之一,我们在每天或许都会遇到,验证码从产生到现在已经衍生出了很多分支、方式。googlekaptcha是一个非常实用的验证码生成类库。
通过灵活的配置生成各种样式的验证码,并将生成的验证码字符串放到HttpSession中,方便获取进行比较。
本文描述在springmvc下快速的将googlekaptcha集成到项目中(单独使用的话在web.xml中配置KaptchaServlet)。下面话不多说了,来一起看看详细的介绍吧。
1.maven依赖
官方提供的pom无法正常使用,使用阿里云仓库对应kaptcha。
com.github.penggle kaptcha ${kaptcha.version}
2.前端
$(function(){ $('#kaptchaImage').click(function(){ $(this).hide().attr('src','${ctx}/captcha-image?'+Math.floor(Math.random()*100)).fadeIn(); event.cancelBubble=true; }); });
3.mvc-context配置
no 45 blue 4 code
更多参数:
水纹com.google.code.kaptcha.impl.WaterRipple
鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
阴影com.google.code.kaptcha.impl.ShadowGimpy
4.服务端
@Controller publicclassCaptchaController{ privatefinalProducercaptchaProducer; @Autowired publicCaptchaController(ProducercaptchaProducer){ this.captchaProducer=captchaProducer; } @RequestMapping(value="captcha-image") publicStringgetKaptchaImage(HttpServletRequestrequest,HttpServletResponseresponse)throwsException{ response.setDateHeader("Expires",0); response.setHeader("Cache-Control","no-store,no-cache,must-revalidate"); response.addHeader("Cache-Control","post-check=0,pre-check=0"); response.setHeader("Pragma","no-cache"); response.setContentType("image/jpeg"); StringcapText=captchaProducer.createText(); request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,capText); BufferedImagebi=captchaProducer.createImage(capText); ServletOutputStreamout=response.getOutputStream(); ImageIO.write(bi,"jpg",out); try{ out.flush(); }finally{ out.close(); } returnnull; } }
5.session中获取验证码
request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
总结
以上就是这篇文章的全部内容了,本文还有许多不足,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。