版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/edtwar/article/details/78808254
图像验证码显示功能使用 google Kaptcha 验证码产品 实现前台验证码显示功能.
1. 坐标添加
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2. SpringMvc 环境配置
<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">green</prop><!--验证码文本字符颜色 默认为Color.BLACK -->
<prop key="kaptcha.session.key">code</prop><!--验证码 -->
<prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop><!--设置字体样式 -->
<prop key="kaptcha.border.thickness"></prop><!--边框粗细度 默认为1 -->
<prop key="kaptcha.producer.impl"></prop><!--验证码生成器 默认为DefaultKaptcha -->
<prop key="kaptcha.textproducer.impl"></prop><!-- 验证码文本生成器 默认为DefaultTextCreator -->
<prop key="kaptcha.textproducer.char.string"></prop><!--验证码文本字符内容范围 默认为abcde2345678gfynmnpwx -->
<prop key="kaptcha.textproducer.char.length">4</prop><!-- 验证码文本字符长度 默认为5 -->
<prop key="kaptcha.textproducer.font.size">40</prop><!--验证码文本字符大小 默认为40 -->
<prop key="kaptcha.textproducer.char.space">6</prop> <!--验证码文本字符间距 默认为2 -->
<prop key="kaptcha.image.width">200</prop> <!--验证码图片宽度 默认为200 -->
<prop key="kaptcha.image.height">50</prop> <!--验证码图片高度 默认为40 -->
</props>
</constructor-arg>
</bean>
</property>
</bean>
3. Controller 准备
@Resource
private Producer captchaProducer;
@RequestMapping("getKaptchaImage")
public void getKaptchaImage(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();
System.out.println("验证码:"+capText);
// store the text in the session
request.getSession().setAttribute(P2pConstant.PICTURE_VERIFY_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();
}
}