<!-- kaptcha 验证码 -->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
<!-- Kaptcha验证码生成器 -->
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha" scope="singleton">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<constructor-arg>
<props>
<prop key="kaptcha.session.key">kaptcha.code</prop>
<!-- 无边框 -->
<prop key="kaptcha.border">no</prop>
<prop key="kaptcha.textproducer.font.color">black</prop>
<!-- 渲染效果:水纹:WaterRipple;鱼眼:FishEyeGimpy;阴影:ShadowGimpy -->
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
<!-- 不要噪点 -->
<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
<prop key="kaptcha.image.width">90</prop>
<prop key="kaptcha.image.height">33</prop>
<prop key="kaptcha.textproducer.font.size">25</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.char.space">5</prop>
<!-- 和登录框背景颜色一致 -->
<prop key="kaptcha.background.clear.from">247,247,247</prop>
<prop key="kaptcha.background.clear.to">247,247,247</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
/**
* 验证码
*
* @param rsp
* @param session
*/
@RequestMapping(value = "captcha.html", method = RequestMethod.GET)
public void kaptcha(HttpServletResponse rsp, HttpSession session) {
try (ServletOutputStream out = rsp.getOutputStream()) {
rsp.setDateHeader("Expires", 0);
rsp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
rsp.addHeader("Cache-Control", "post-check=0, pre-check=0");
rsp.setHeader("Pragma", "no-cache");
rsp.setContentType("image/jpeg");
String capText = captchaProducer.createText();
//将验证码存入shiro 登录用户的session
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
BufferedImage image = captchaProducer.createImage(capText);
ImageIO.write(image, "jpg", out);
out.flush();
} catch (IOException e) {
throw new SystemException(e);
}
}