如何正确的使用kaptcha验证码组件

本篇文章为大家展示了如何正确的使用kaptcha验证码组件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

一、简单的jsp-servlet项目

1.添加jar包依赖

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

<!-- kaptcha --> 
<dependency> 
  <groupId>com.google.code.kaptcha</groupId> 
  <artifactId>kaptcha</artifactId> 
  <version>2.3.2</version> 
</dependency>

如果是非maven管理的项目,则直接在官网下载kaptcha的jar包,然后添加到项目lib库中,下载地址:

http://code.google.com/p/kaptcha/downloads/list

2.配置web.xml

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

<servlet> 
  <servlet-name>Kaptcha</servlet-name> 
  <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
  <servlet-name>Kaptcha</servlet-name> 
  <url-pattern>/kaptcha.jpg</url-pattern> 
</servlet-mapping>

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

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

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

<servlet> 
  <servlet-name>Kaptcha</servlet-name> 
  <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> 
  <init-param> 
    <param-name>kaptcha.image.width</param-name> 
    <param-value>200</param-value> 
    <description>Width in pixels of the kaptcha image.</description> 
  </init-param> 
  <init-param> 
    <param-name>kaptcha.image.height</param-name> 
    <param-value>50</param-value> 
    <description>Height in pixels of the kaptcha image.</description> 
  </init-param> 
  <init-param> 
    <param-name>kaptcha.textproducer.char.length</param-name> 
    <param-value>4</param-value> 
    <description>The number of characters to display.</description> 
  </init-param> 
  <init-param> 
    <param-name>kaptcha.noise.impl</param-name> 
    <param-value>com.google.code.kaptcha.impl.NoNoise</param-value> 
    <description>The noise producer.</description> 
  </init-param> 
</servlet>

具体的配置参数参见:http://code.google.com/p/kaptcha/wiki/ConfigParameters

3.页面调用

<form action="submit.action"> 
  <input type="text" name="kaptcha" value="" /><img src="kaptcha.jpg" /> 
</form>

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

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

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

5.实现页面验证码刷新

<img src="kaptcha.jpg" width="200" id="kaptchaImage" title="看不清,点击换一张" /> 
<script type="text/javascript"> 
  $(function() { 
    $('#kaptchaImage').click(function() {$(this).attr('src','kaptcha.jpg?' + Math.floor(Math.random() * 100));}); 
  }); 
</script> 
<br /><small>看不清,点击换一张</small>

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

二、Spring mvc项目中使用kaptcha

1.添加captchaProducer bean定义

<!-- 配置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">100</prop> 
          <prop key="kaptcha.image.height">50</prop> 
          <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop> 
          <prop key="kaptcha.textproducer.char.string">0123456789abcdefghijklmnopqrstuvwxyz</prop> 
          <prop key="kaptcha.textproducer.char.length">4</prop> 
        </props> 
      </constructor-arg> 
    </bean> 
  </property> 
</bean>

2.生成验证码的Controller

import java.awt.image.BufferedImage;  
import javax.imageio.ImageIO; 
import javax.servlet.ServletOutputStream; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse;  
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.servlet.ModelAndView;  
import com.google.code.kaptcha.Constants; 
import com.google.code.kaptcha.Producer;  
/** 
 * ClassName: CaptchaImageCreateController <br/> 
 * Function: 生成验证码Controller. <br/> 
 * date: 2013-12-10 上午11:37:42 <br/> 
 * 
 * @author chenzhou1025@126.com 
 */ 
@Controller 
public class CaptchaImageCreateController { 
  private Producer captchaProducer = null;  
  @Autowired 
  public void setCaptchaProducer(Producer captchaProducer){ 
    this.captchaProducer = captchaProducer; 
  }  
  @RequestMapping("/kaptcha.jpg") 
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{ 
    // Set to expire far in the past. 
    response.setDateHeader("Expires", 0); 
    // Set standard 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). 
    response.addHeader("Cache-Control", "post-check=0, pre-check=0"); 
    // Set standard HTTP/1.0 no-cache header. 
    response.setHeader("Pragma", "no-cache");  
    // return a jpeg 
    response.setContentType("image/jpeg");  
    // create the text for the image 
    String capText = captchaProducer.createText();  
    // store the text in the session 
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
    // create the image with the text 
    BufferedImage bi = captchaProducer.createImage(capText);  
    ServletOutputStream out = response.getOutputStream();  
    // write the data out 
    ImageIO.write(bi, "jpg", out); 
    try { 
      out.flush(); 
    } finally { 
      out.close(); 
    } 
    return null; 
  } 
}

3.校验用户输入的Controller

/**
 * ClassName: LoginController <br/>
 * Function: 登录Controller. <br/>
 * date: 2013-12-10 上午11:41:43 <br/>
 *
 * @author chenzhou1025@126.com
 */
@Controller
@RequestMapping("/login")
public class LoginController {
	/**
	 * loginCheck:ajax异步校验登录请求. <br/>
	 *
	 * @author chenzhou1025@126.com
	 * @param request
	 * @param username 用户名
	 * @param password 密码
	 * @param kaptchaReceived 验证码
	 * @return 校验结果
	 * @since 2013-12-10
	 */
	@RequestMapping(value = "check", method = RequestMethod.POST)
	@ResponseBody
	public String loginCheck(HttpServletRequest request,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "kaptcha", required = true) String kaptchaReceived){
		//用户输入的验证码的值
		String kaptchaExpected = (String) request.getSession().getAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		//校验验证码是否正确
		if (kaptchaReceived == null || !kaptchaReceived.equals(kaptchaExpected)) {
			return "kaptcha_error";//返回验证码错误
		}
		//校验用户名密码
		// ……
		// ……
		return "success"; //校验通过返回成功
	}
}

上述内容就是如何正确的使用kaptcha验证码组件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。