配置生成规则
<!-- 配置验证码 -->
<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">no</prop>
<!-- 图片宽度 -->
<prop key="kaptcha.image.width">95</prop>
<!-- 图片高度 -->
<prop key="kaptcha.image.height">45</prop>
<!-- 验证码背景颜色渐变,开始颜色 -->
<prop key="kaptcha.background.clear.from">248,248,248</prop>
<!-- 验证码背景颜色渐变,结束颜色 -->
<prop key="kaptcha.background.clear.to">248,248,248</prop>
<!-- 验证码的字符 -->
<prop key="kaptcha.textproducer.char.string">
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</prop>
<!-- 验证码字体颜色 -->
<prop key="kaptcha.textproducer.font.color">0,0,255</prop>
<!-- 验证码的效果 -->
<prop key="kaptcha.obscurificator.impl">
com.google.code.kaptcha.impl.ShadowGimpy
</prop>
<!-- 验证码字体大小 -->
<prop key="kaptcha.textproducer.font.size">35</prop>
<!-- 验证码字数 -->
<prop key="kaptcha.textproducer.char.length">4</prop>
<!-- 验证码文字间距 -->
<prop key="kaptcha.textproducer.char.space">2</prop>
<!-- 验证码字体 -->
<prop key="kaptcha.textproducer.font.names">
new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
</prop>
<!-- 不加噪声 -->
<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
使用方法
/**
* 生成带验证码的图片
*/
@GetMapping(value = "/getCaptchaImage.pub")
public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
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();
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_DATE, new Date());
BufferedImage bi = captchaProducer.createImage(capText);
try (ServletOutputStream out = response.getOutputStream()) {
ImageIO.write(bi, "jpeg", out);
out.flush();
}
}