图形验证码---
- 在pom.xml中引入依赖:
<!--kaptcha图形验证码-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>
2.在applicationContext.xml中写入bean配置
<!--图形验证码-->
<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">blue</prop>
<prop key="kaptcha.image.width">125</prop>
<prop key="kaptcha.image.height">55</prop>
<prop key="kaptcha.textproducer.font.size">45</prop>
<prop key="kaptcha.session.key">code</prop>
<prop key="kaptcha.textproducer.char.length">4</prop>
<prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
</props>
</constructor-arg>
</bean>
</property>
</bean>
3.编写控制器获取验证码:
@Autowired
private Producer captchaProducer;//验证码使用的类,与xml声明bean一致
// 获取验证码
@RequestMapping("/getcode")
public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 浏览器缓存页面的时限,0表示不进行缓存。
response.setDateHeader("Expires", 0);
// Cache-Control:指定请求和响应遵循的缓存机制
// no-cache:强制客户端跳过'检查缓存是否有需要的数据',每次请求都必须重新发送
//must-revalidate:作用与no-cache相同,更严格,强制意味更明显
//no-store:缓存将不存储response,包括header和body
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// post-check:缓冲内容在显示给用户之前必须更新(前提内容被增删改)
// pre-check:与post-check效果相似,但可发生在显示给用户之后
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// 指定客户端不缓存页面
response.setHeader("Pragma", "no-cache");
// 设置输出流内容格式为图片格式
response.setContentType("image/jpeg");
// 生成验证码
String capText = captchaProducer.createText();
// 将验证码放入session中
request.getSession().setAttribute(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();//关闭流
}
//打印session中的验证码
System.out.println("Captchca:" + request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
}
4.页面编写
<img src="${pageContext.request.contextPath}/getcode" id="code" width="100px" height="30px">
<script type="text/javascript">
$(function(){
$("#code").click(function () {
var ran = Math.floor(Math.random() * 100);//为了不让验证码图片被缓存,需要在请求后边加入随机数
$('#code').attr('src','${pageContext.request.contextPath}/getcode?' + ran);
});
})
</script>