有理走遍天下
先说原理,验证码生成逻辑如下:
首先请求地址,服务端返回一个页面地址,页面端页面内容包含以下内容:
其中<img />标签属性的src指向一个后端controller,该后端内容负责生成验证码并放入session中,然后返回至页面(两个作用:1,用来前端显示 2,用来返回至登录controller和用户输入的验证码做比较),(我们知道session会在一整个会话过程结束之后才会销毁),当用户输入验证码之后,会把用户输入的内容,和session中存放生成验证码信息做比较。整个过程如上。下面说说具体实现。
第一:要用到kaptcha,那么必须先导入相关jar,这里只说maven项目为例,那么必须现在pom.xml文件
中写入kaptcha相关配置文件:如下:
<dependency>
<groupId>com.google.code.kaptcha</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
接下来配置appliCationContext.xml文件加入一下配置,
<!--登录页面校验码配置 使用com.google.code.kaptcha -->
<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> 图片边框(yes/no)
<prop key="kaptcha.border.color">105,179,90</prop> 边框颜色
<prop key="kaptcha.textproducer.font.color">blue</prop> 字体颜色
<prop key="kaptcha.textproducer.font.size">30</prop> 字体大小
<prop key="kaptcha.textproducer.char.space">10</prop> 字体间隔
<prop key="kaptcha.session.key">code</prop> session key
<prop key="kaptcha.textproducer.char.length">4</prop> 验证码长度
<prop key="kaptcha.image.width">93</prop> 图片宽
<prop key="kaptcha.image.height">37</prop> 图片高
</props>
</constructor-arg>
</bean>
</property>
</bean>
接下来开下相应的Controller代码:
//随机生成验证码的控制层
@Controller
@RequestMapping("/kaptcha")
public class CaptchaController {
@Autowired
private Producer captchaProducer/* = null */;
@RequestMapping(value = "/image", method = RequestMethod.GET)
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
System.out.println("*****session中获取的验证码是: " + code + "*****");
response.setDateHeader("Expires", 0); //禁止服务缓存
// Set standard HTTP/1.1 no-cache headers. 设置标准的的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). 设置IE扩展 HTTP/1.1
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header. 设置HTTP/1.0不缓存图片
response.setHeader("Pragma", "no-cache");
// return a jpeg 返回一个jpeg,默认为text/html
response.setContentType("image/jpeg");
// create the text for the image 为图片创建文本
String capText = captchaProducer.createText();
// store the text in the session 将文本保存到session中,这里就包含了保中的静态变量
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
// create the image with the text 差UN关键带有文本的图片
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
// write the data out 图片输出流
ImageIO.write(bi, "JPEG", out);
try {
out.flush();
} finally {
out.close();
}
}
}