本文主要是介绍Spring 验证码(kaptcha),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先引入需要的jar包:
<dependency><groupId>com.github.axet</groupId><artifactId>kaptcha</artifactId><version>0.0.9</version></dependency>
配置验证码相关设置:
<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">red</prop><prop key="kaptcha.image.width">65</prop><prop key="kaptcha.textproducer.font.size">26</prop><prop key="kaptcha.image.height">30</prop><prop key="kaptcha.session.key">verify</prop><prop key="kaptcha.textproducer.char.length">4</prop><prop key="kaptcha.textproducer.font.names">Arial, Courier</prop><prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.FishEyeGimpy</prop><prop key="kaptcha.textproducer.char.string">abcd234567gfynmnpwx</prop></props></constructor-arg></bean></property></bean>
生成验证码:
@RequestMapping(value = "/getVerify.html")public ModelAndView getVerify(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("type") String type) throws Exception {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");String capText = captchaProducer.createText();if (type.equals("mobile")) {request.getSession().setAttribute(Constants.MOBILE_KAPTCHA_SESSION_KEY, capText);} else {request.getSession().setAttribute(Constants.EMAIL_KAPTCHA_SESSION_KEY, capText);}BufferedImage bi = captchaProducer.createImage(capText);ServletOutputStream out = response.getOutputStream();ImageIO.write(bi, "jpg", out);try {out.flush();} finally {out.close();}return null;}
通过localhost:8080/getVerify.html 获取验证码
这篇关于Spring 验证码(kaptcha)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!