---
title: "kaptcha验证码组件使用简介"
author: "tmuffamd"
date: "2018-03-01T16:39:14Z"
tags: []
categories: ["Web前端"]
slug: "kaptcha"
draft: false
lastmod: "2018-03-01T16:39:14Z"
id: 2411929
url: "https://tmuffamd.iteye.com/blog/2411929"
---

Kaptcha是一个基于SimpleCaptcha的验证码开源项目。

官网地址：[http://code.google.com/p/kaptcha/](http://code.google.com/p/kaptcha/)

 

kaptcha的使用比较方便，只需添加jar包依赖之后简单地配置就可以使用了。kaptcha所有配置都可以通过web.xml来完成，如果你的项目中使用了Spring MVC，那么则有另外的一种方式来实现。

 

**一、简单的jsp-servlet项目**

**1.添加jar包依赖**

如果你使用maven来统一管理jar包，则在工程的pom.xml中添加dependency

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

1. &lt;!-- kaptcha --&gt;
2. &lt;dependency&gt;
3. &lt;groupId&gt;com.google.code.kaptcha&lt;/groupId&gt;
4. &lt;artifactId&gt;kaptcha&lt;/artifactId&gt;
5. &lt;version&gt;2.3.2&lt;/version&gt;
6. &lt;/dependency&gt;

如果是非maven管理的项目，则直接在官网下载kaptcha的jar包，然后添加到项目lib库中，下载地址：[http://code.google.com/p/kaptcha/downloads/list](http://code.google.com/p/kaptcha/downloads/list)

 

 

**2.配置web.xml**

上面说了，kaptcha都是在web.xml中配置，我们必须在web.xml中配置kaptcha的servlet，具体如下：

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

1. &lt;servlet&gt;
2. &lt;servlet-name&gt;Kaptcha&lt;/servlet-name&gt;
3. &lt;servlet-class&gt;com.google.code.kaptcha.servlet.KaptchaServlet&lt;/servlet-class&gt;
4. &lt;/servlet&gt;
5. &lt;servlet-mapping&gt;
6. &lt;servlet-name&gt;Kaptcha&lt;/servlet-name&gt;
7. &lt;url-pattern&gt;/kaptcha.jpg&lt;/url-pattern&gt;
8. &lt;/servlet-mapping&gt;

其中servlet的url-pattern可以自定义。

 

kaptcha所有的参数都有默认的配置，如果我们不显示配置的话，会采取默认的配置。

如果要显示配置kaptcha，在配置kaptcha对应的Servlet时，在init-param增加响应的参数配置即可。示例如下：

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

01. &lt;servlet&gt;
02. &lt;servlet-name&gt;Kaptcha&lt;/servlet-name&gt;
03. &lt;servlet-class&gt;com.google.code.kaptcha.servlet.KaptchaServlet&lt;/servlet-class&gt;
04. &lt;init-param&gt;
05. &lt;param-name&gt;kaptcha.image.width&lt;/param-name&gt;
06. &lt;param-value&gt;200&lt;/param-value&gt;
07. &lt;description&gt;Width in pixels of the kaptcha image.&lt;/description&gt;
08. &lt;/init-param&gt;
09. &lt;init-param&gt;
10. &lt;param-name&gt;kaptcha.image.height&lt;/param-name&gt;
11. &lt;param-value&gt;50&lt;/param-value&gt;
12. &lt;description&gt;Height in pixels of the kaptcha image.&lt;/description&gt;
13. &lt;/init-param&gt;
14. &lt;init-param&gt;
15. &lt;param-name&gt;kaptcha.textproducer.char.length&lt;/param-name&gt;
16. &lt;param-value&gt;4&lt;/param-value&gt;
17. &lt;description&gt;The number of characters to display.&lt;/description&gt;
18. &lt;/init-param&gt;
19. &lt;init-param&gt;
20. &lt;param-name&gt;kaptcha.noise.impl&lt;/param-name&gt;
21. &lt;param-value&gt;com.google.code.kaptcha.impl.NoNoise&lt;/param-value&gt;
22. &lt;description&gt;The noise producer.&lt;/description&gt;
23. &lt;/init-param&gt;
24. &lt;/servlet&gt;

具体的配置参数参见：[http://code.google.com/p/kaptcha/wiki/ConfigParameters](http://code.google.com/p/kaptcha/wiki/ConfigParameters)

 

**3.页面调用**

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

1. &lt;form action="submit.action"&gt;
2. &lt;input type="text" name="kaptcha" value="" /&gt;&lt;img src="kaptcha.jpg" /&gt;
3. &lt;/form&gt;

 

**4.在submit的action方法中进行验证码校验**

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

1. //从session中取出servlet生成的验证码text值
2. String kaptchaExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA\_SESSION\_KEY);
3. //获取用户页面输入的验证码
4. String kaptchaReceived = request.getParameter("kaptcha");
5. //校验验证码是否正确
6. if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)){
7. setError("kaptcha", "Invalid validation code.");
8. }

注：确保JDK设置了 **-Djava.awt.headless=true**

 

**5.实现页面验证码刷新**

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

1. &lt;img src="kaptcha.jpg" width="200" id="kaptchaImage" title="看不清，点击换一张" /&gt;
2. &lt;script type="text/javascript"&gt;
3. $(function() {
4. $('#kaptchaImage').click(function() {$(this).attr('src','kaptcha.jpg?' + Math.floor(Math.random() * 100));});
5. });
6. &lt;/script&gt;
7. &lt;br /&gt;&lt;small&gt;看不清，点击换一张&lt;/small&gt;

注：为了避免浏览器的缓存，可以在验证码请求url后添加随机数

 

**二、Spring mvc项目中使用kaptcha**

**1.添加captchaProducer bean定义**

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

01. &lt;!-- 配置kaptcha验证码 --&gt;
02. &lt;bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"&gt;
03. &lt;property name="config"&gt;
04. &lt;bean class="com.google.code.kaptcha.util.Config"&gt;
05. &lt;constructor-arg type="java.util.Properties"&gt;
06. &lt;props&gt;
07. &lt;prop key="kaptcha.image.width"&gt;100&lt;/prop&gt;
08. &lt;prop key="kaptcha.image.height"&gt;50&lt;/prop&gt;
09. &lt;prop key="kaptcha.noise.impl"&gt;com.google.code.kaptcha.impl.NoNoise&lt;/prop&gt;
10. &lt;prop key="kaptcha.textproducer.char.string"&gt;0123456789abcdefghijklmnopqrstuvwxyz&lt;/prop&gt;
11. &lt;prop key="kaptcha.textproducer.char.length"&gt;4&lt;/prop&gt;
12. &lt;/props&gt;
13. &lt;/constructor-arg&gt;
14. &lt;/bean&gt;
15. &lt;/property&gt;
16. &lt;/bean&gt;

**2.生成验证码的Controller**

Java代码  [![收藏代码](http://chenzhou123520.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. /\**
13. * ClassName: CaptchaImageCreateController &lt;br/&gt;
14. * Function: 生成验证码Controller. &lt;br/&gt;
15. * date: 2013-12-10 上午11:37:42 &lt;br/&gt;
16. \*
17. * @author chenzhou1025@126.com
18. \*/
19. @Controller
20. public class CaptchaImageCreateController {
21. private Producer captchaProducer = null;
22. @Autowired
23. public void setCaptchaProducer(Producer captchaProducer){
24. this.captchaProducer = captchaProducer;
25. }
26. @RequestMapping("/kaptcha.jpg")
27. public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
28. // Set to expire far in the past.
29. response.setDateHeader("Expires", 0);
30. // Set standard HTTP/1.1 no-cache headers.
31. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
32. // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
33. response.addHeader("Cache-Control", "post-check=0, pre-check=0");
34. // Set standard HTTP/1.0 no-cache header.
35. response.setHeader("Pragma", "no-cache");
36. // return a jpeg
37. response.setContentType("image/jpeg");
38. // create the text for the image
39. String capText = captchaProducer.createText();
40. // store the text in the session
41. request.getSession().setAttribute(Constants.KAPTCHA\_SESSION\_KEY, capText);
42. // create the image with the text
43. BufferedImage bi = captchaProducer.createImage(capText);
44. ServletOutputStream out = response.getOutputStream();
45. // write the data out
46. ImageIO.write(bi, "jpg", out);
47. try {
48. out.flush();
49. } finally {
50. out.close();
51. }
52. return null;
53. }
54. }

 

**3.校验用户输入的Controller**

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

01. /\**
02. * ClassName: LoginController &lt;br/&gt;
03. * Function: 登录Controller. &lt;br/&gt;
04. * date: 2013-12-10 上午11:41:43 &lt;br/&gt;
05. \*
06. * @author chenzhou1025@126.com
07. \*/
08. @Controller
09. @RequestMapping("/login")
10. public class LoginController {
11. /\**
12. * loginCheck:ajax异步校验登录请求. &lt;br/&gt;
13. \*
14. * @author chenzhou1025@126.com
15. * @param request
16. * @param username 用户名
17. * @param password 密码
18. * @param kaptchaReceived 验证码
19. * @return 校验结果
20. * @since 2013-12-10
21. \*/
22. @RequestMapping(value = "check", method = RequestMethod.POST)
23. @ResponseBody
24. public String loginCheck(HttpServletRequest request,
25. @RequestParam(value = "username", required = true) String username,
26. @RequestParam(value = "password", required = true) String password,
27. @RequestParam(value = "kaptcha", required = true) String kaptchaReceived){
28. //用户输入的验证码的值
29. String kaptchaExpected = (String) request.getSession().getAttribute(
30. com.google.code.kaptcha.Constants.KAPTCHA\_SESSION\_KEY);
31. //校验验证码是否正确
32. if (kaptchaReceived == null || !kaptchaReceived.equals(kaptchaExpected)) {
33. return "kaptcha\_error";//返回验证码错误
34. }
35. //校验用户名密码
36. // ……
37. // ……
38. return "success"; //校验通过返回成功
39. }
40. }