---
title: "kaptcha 验证码在spring mvc 中的使用"
author: "paskaa"
date: "2012-07-04T10:11:45Z"
tags: []
categories: ["Web前端"]
slug: "kaptcha-spring-mvc"
draft: false
lastmod: "2012-07-04T10:11:45Z"
id: 1576244
url: "https://paskaa.iteye.com/blog/1576244"
---

kaptcha 是一个非常实用的验证码生成工具。有了它，你可以生成各种样式的验证码，因为它是可配置的。kaptcha工作的原理是调用 com.google.code.kaptcha.servlet.KaptchaServlet，生成一个图片。同时将生成的验证码字符串放到 HttpSession中。

使用kaptcha可以方便的配置：

 

- 验证码的字体
- 验证码字体的大小
- 验证码字体的字体颜色
- 验证码内容的范围(数字，字母，中文汉字！)
- 验证码图片的大小，边框，边框粗细，边框颜色
- 验证码的干扰线(可以自己继承com.google.code.kaptcha.NoiseProducer写一个自定义的干扰线)
- 验证码的样式(鱼眼样式、3D、普通模糊……当然也可以继承com.google.code.kaptcha.GimpyEngine自定义样式)

……

详细信息请看下面的web.xml文件

下面介绍一下用法:

1.首先去官网下载jar:[http://code.google.com/p/kaptcha/](http://code.google.com/p/kaptcha/)

2.建立一个web项目，导入[kaptcha-2.3.jar到环境变量中。]()

3.配置web.xml文件

Xml代码  [![收藏代码](http://ttaale.iteye.com/images/icon_star.png)]()

01. &lt;!--Kaptcha 验证码  --&gt; &lt;!--
02. &lt; servlet &gt;
03. &lt; servlet-name &gt; kaptcha &lt;/ servlet-name &gt;
04. &lt; servlet-class &gt; com.google.code.kaptcha.servlet.KaptchaServlet &lt;/ servlet-class &gt;
05. &lt; init-param &gt;
06. &lt; param-name &gt; kaptcha.border &lt;/ param-name &gt;
07. &lt; param-value &gt; no &lt;/ param-value &gt;
08. &lt;/ init-param &gt;
09. &lt; init-param &gt;
10. &lt; param-name &gt; kaptcha.border.color &lt;/ param-name &gt;
11. &lt; param-value &gt; 105,179,90 &lt;/ param-value &gt;
12. &lt;/ init-param &gt;
13. &lt; init-param &gt;
14. &lt; param-name &gt; kaptcha.textproducer.font.color &lt;/ param-name &gt;
15. &lt; param-value &gt; red &lt;/ param-value &gt;
16. &lt;/ init-param &gt;
17. &lt; init-param &gt;
18. &lt; param-name &gt; kaptcha.image.width &lt;/ param-name &gt;
19. &lt; param-value &gt; 250 &lt;/ param-value &gt;
20. &lt;/ init-param &gt;
21. &lt; init-param &gt;
22. &lt; param-name &gt; kaptcha.image.height &lt;/ param-name &gt;
23. &lt; param-value &gt; 90 &lt;/ param-value &gt;
24. &lt;/ init-param &gt;
25. &lt; init-param &gt;
26. &lt; param-name &gt; kaptcha.textproducer.font.size &lt;/ param-name &gt;
27. &lt; param-value &gt; 70 &lt;/ param-value &gt;
28. &lt;/ init-param &gt;
29. &lt; init-param &gt;
30. &lt; param-name &gt; kaptcha.session.key &lt;/ param-name &gt;
31. &lt; param-value &gt; code &lt;/ param-value &gt;
32. &lt;/ init-param &gt;
33. &lt; init-param &gt;
34. &lt; param-name &gt; kaptcha.textproducer.char.length &lt;/ param-name &gt;
35. &lt; param-value &gt; 4 &lt;/ param-value &gt;
36. &lt;/ init-param &gt;
37. &lt; init-param &gt;
38. &lt; param-name &gt; kaptcha.textproducer.font.names &lt;/ param-name &gt;
39. &lt; param-value &gt; 宋体,楷体,微软雅黑 &lt;/ param-value &gt;
40. &lt;/ init-param &gt;
41. &lt;/ servlet &gt;

Xml代码

Xml代码  [![收藏代码](http://ttaale.iteye.com/images/icon_star.png)]()

1. &lt; servlet-mapping &gt;
2. &lt; servlet-name &gt; kaptcha &lt;/ servlet-name &gt;
3. &lt; url-pattern &gt; /ClinicCountManager/kaptcha.jpg &lt;/ url-pattern &gt;
4. lt;/servlet-mapping&gt;

 

jsp 页面使用

Java代码  [![收藏代码](http://ttaale.iteye.com/images/icon_star.png)]()

01. &lt;table&gt;
02. &lt;tr&gt;
03. &lt;td&gt;&lt;img src="/ClinicCountManager/kaptcha.jpg" &gt;&lt;/td&gt;
04. &lt;td valign="top" &gt;
05. &lt;form method="POST" &gt;
06. &lt;br&gt;sec code:&lt;input type="text"  name= "kaptchafield" &gt;&lt;br /&gt;
07. &lt;input type="submit"  name= "submit" &gt;
08. &lt;/form&gt;
09. &lt;/td&gt;
10. &lt;/tr&gt;
11. &lt;/table&gt;
12. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;
13. &lt;%
14. String c = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA\_SESSION\_KEY);
15. String parm = (String) request.getParameter("kaptchafield" );
16. out.println("Parameter: "  + parm +  " ? Session Key: "  + c +  " : " );
17. if  (c !=  null  && parm !=  null ) {
18. if  (c.equals(parm)) {
19. out.println("&lt;b&gt;true&lt;/b&gt;" );
20. } else  {
21. out.println("&lt;b&gt;false&lt;/b&gt;" );
22. }
23. %&gt;

 

上面的配置在普通jsp环境下面是有效的，如果在spring mvc环境下，则取不到session值，对于sping mvc环境验证码配置如下：

１.不用在web.xml进行相关配置，在applicationContext.xml中配置

 

Xml代码 

Xml代码  [![收藏代码](http://ttaale.iteye.com/images/icon_star.png)]()

01. &lt; bean   id = "captchaProducer"   class = "com.google.code.kaptcha.impl.DefaultKaptcha" &gt;
02. &lt; property   name = "config" &gt;
03. &lt; bean   class = "com.google.code.kaptcha.util.Config" &gt;
04. &lt; constructor-arg &gt;
05. &lt; props &gt;
06. &lt; prop   key = "kaptcha.border" &gt; no &lt;/ prop &gt;
07. &lt; prop   key = "kaptcha.border.color" &gt; 105,179,90 &lt;/ prop &gt;
08. &lt; prop   key = "kaptcha.textproducer.font.color" &gt; red &lt;/ prop &gt;
09. &lt; prop   key = "kaptcha.image.width" &gt; 250 &lt;/ prop &gt;
10. &lt; prop   key = "kaptcha.textproducer.font.size" &gt; 90 &lt;/ prop &gt;
11. &lt; prop   key = "kaptcha.image.height" &gt; 90 &lt;/ prop &gt;
12. &lt; prop   key = "kaptcha.session.key" &gt; code &lt;/ prop &gt;
13. &lt; prop   key = "kaptcha.textproducer.char.length" &gt; 4 &lt;/ prop &gt;
14. &lt; prop   key = "kaptcha.textproducer.font.names" &gt; 宋体,楷体,微软雅黑 &lt;/ prop &gt;
15. &lt;/ props &gt;
16. &lt;/ constructor-arg &gt;
17. &lt;/ bean &gt;
18. &lt;/ property &gt;
19. &lt;/ bean &gt;

 

新建生成图片控制类

Java代码  [![收藏代码](http://ttaale.iteye.com/images/icon_star.png)]()

01. import  java.awt.image.BufferedImage;
02. import  javax.imageio.ImageIO;
03. import  javax.servlet.ServletOutputStream;
04. import  javax.servlet.http.HttpServletRequest;
05. import  javax.servlet.http.HttpServletResponse;
06. import  org.springframework.beans.factory.annotation.Autowired;
07. import  org.springframework.stereotype.Controller;
08. import  org.springframework.web.bind.annotation.RequestMapping;
09. import  org.springframework.web.servlet.ModelAndView;
10. import  com.google.code.kaptcha.Constants;
11. import  com.google.code.kaptcha.Producer;
12. @Controller
13. @RequestMapping ( "/" )
14. public   class  CaptchaImageCreateController {
15. private  Producer captchaProducer =  null ;
16. @Autowired
17. public   void  setCaptchaProducer(Producer captchaProducer) {
18. this .captchaProducer = captchaProducer;
19. }
20. @RequestMapping ( "/captcha-image" )
21. public  ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)  throws  Exception {
22. response.setDateHeader("Expires" ,  0 );
23. // Set standard HTTP/1.1 no-cache headers.
24. response.setHeader("Cache-Control" ,  "no-store, no-cache, must-revalidate" );
25. // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
26. response.addHeader("Cache-Control" ,  "post-check=0, pre-check=0" );
27. // Set standard HTTP/1.0 no-cache header.
28. response.setHeader("Pragma" ,  "no-cache" );
29. // return a jpeg
30. response.setContentType("image/jpeg" );
31. // create the text for the image
32. String capText = captchaProducer.createText();
33. // store the text in the session
34. request.getSession().setAttribute(Constants.KAPTCHA\_SESSION\_KEY, capText);
35. // create the image with the text
36. BufferedImage bi = captchaProducer.createImage(capText);
37. ServletOutputStream out = response.getOutputStream();
38. // write the data out
39. ImageIO.write(bi, "jpg" , out);
40. try  {
41. out.flush();
42. } finally  {
43. out.close();
44. }
45. return   null ;
46. }
47. }

 前台调用方式

 

Java代码

Java代码  [![收藏代码](http://ttaale.iteye.com/images/icon_star.png)]()

01. &lt;div  class = "chknumber" &gt;
02. &lt;label&gt;验证码：
03. &lt;input name="kaptcha"  type= "text"  id= "kaptcha"  maxlength= "4"   class = "chknumber\_input"  /&gt;
04. &lt;/label&gt;
05. &lt;img src="/ClinicCountManager/captcha-image.do"  width= "55"  height= "20"  id= "kaptchaImage"   style= "margin-bottom: -3px" /&gt;
06. &lt;script type="text/javascript" &gt;
07. $(function(){
08. $('#kaptchaImage' ).click(function () { //生成验证码
09. $(this ).hide().attr( 'src' ,  '/ClinicCountManager/captcha-image.do?'  + Math.floor(Math.random()* 100 ) ).fadeIn(); })
10. });
11. &lt;/script&gt;
12. &lt;/div&gt;

 取验证码的方式

 

Java代码

Java代码  [![收藏代码](http://ttaale.iteye.com/images/icon_star.png)]()

1. String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA\_SESSION\_KEY);