标签:验证码
项目中配置 Kaptcha 验证码分一下几步:
1,添加Maven依赖
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2,spring容器中注入kaptcha,自定义其相关属性
<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
<property name="config">
<bean class="com.google.code.kaptcha.util.Config">
<!--通过构造函数注入属性值 -->
<constructor-arg type="java.util.Properties">
<props>
<!-- 验证码宽度 -->
<prop key="kaptcha.image.width">150</prop>
<!-- 验证码高度 -->
<prop key="kaptcha.image.height">60</prop>
<!-- 生成验证码内容范围 -->
<prop key="kaptcha.textproducer.char.string">abcde2345678gfynmnpwx</prop>
<!-- 验证码个数 -->
<prop key="kaptcha.textproducer.char.length">5</prop>
<!-- 是否有边框 -->
<prop key="kaptcha.border">no</prop>
<!-- 验证码字体颜色 -->
<prop key="kaptcha.textproducer.font.color">red</prop>
<!-- 验证码字体大小 -->
<prop key="kaptcha.textproducer.font.size">35</prop>
<!-- 验证码所属字体样式 -->
<prop key="kaptcha.textproducer.font.names">Arial, Courier</prop>
<prop key="kaptcha.background.clear.from">white</prop>
<prop key="kaptcha.background.clear.to">white</prop>
<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
<prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
<!-- 干扰线颜色 -->
<prop key="kaptcha.noise.color">red</prop>
<!-- 验证码文本字符间距 -->
<prop key="kaptcha.textproducer.char.space">4</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
3 在控制器中写获取验证图片的方法
/**
* Kaptcha 验证码
*/
@Autowired
private DefaultKaptcha captchaProducer;
@RequestMapping(value = "captcha.htm", method = RequestMethod.GET)
public void captcha(HttpServletRequest request, HttpServletResponse response)
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();
request.getSession().setAttribute(
com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
4,前台调用
<img id="captcha" style="cursor: pointer; cursor: hand; margin-top: -13px;"
onclick=""http://blog.51cto.com/viewpic.php?refimg=" + this.src=‘${BASE_PATH}/admin/captcha.htm?‘+Math.random();"
src="${BASE_PATH}/captcha.htm">
5,后台验证时从Session中获取验证码
String kaptcha = (String) request.getSession().getAttribute(
com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
本文出自 “9884307” 博客,请务必保留此出处http://9894307.blog.51cto.com/9884307/1762201
标签:验证码
原文地址:http://9894307.blog.51cto.com/9884307/1762201