spring mvc 使用kaptcha生成验证码

By default, Kaptcha is very easy to setup and use and the default output produces a captcha that should be fairly hard to bust. The captcha's it produces by default look very similar to the one above. If you would like to change the look of the output, there is several configuration options and the framework is modular so you can write your own morphing code.
 
下载kaptcha-2.3.2.jar(或直接通过该文章附件下载)
http://code.google.com/p/kaptcha/downloads/list
1.spring 配置文件 applicationContext.xml
[html]  view plain copy
 
  1. <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  
  2.         <property name="config">  
  3.             <bean class="com.google.code.kaptcha.util.Config">  
  4.                 <constructor-arg>  
  5.                     <props>  
  6.                         <prop key="kaptcha.border">yes</prop>  
  7.                         <prop key="kaptcha.border.color">105,179,90</prop>  
  8.                         <prop key="kaptcha.textproducer.font.color">blue</prop>  
  9.                         <prop key="kaptcha.image.width">125</prop>  
  10.                         <prop key="kaptcha.image.height">45</prop>  
  11.                         <prop key="kaptcha.textproducer.font.size">45</prop>  
  12.                         <prop key="kaptcha.session.key">code</prop>  
  13.                         <prop key="kaptcha.textproducer.char.length">4</prop>  
  14.                         <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  
  15.                     </props>  
  16.                 </constructor-arg>  
  17.             </bean>  
  18.         </property>  
  19.     </bean> 
2. Controller的实现
[java]  view plain copy
 
  1. package com.vopzoon.app.base.captcha;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4.   
  5. import javax.imageio.ImageIO;  
  6. import javax.servlet.ServletOutputStream;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9. import javax.servlet.http.HttpSession;  
  10.   
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.stereotype.Controller;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15.   
  16. import com.google.code.kaptcha.Constants;  
  17. import com.google.code.kaptcha.Producer;  
  18.   
  19. /** 
  20.  * 防止Captcha机器人登陆 
  21.  * @author liuwang 
  22.  * 
  23.  */  
  24. @Controller  
  25. @RequestMapping("/kaptcha/*")  
  26. public class CaptchaController {  
  27.       
  28.     @Autowired  
  29.     private Producer captchaProducer = null;  
  30.   
  31.     @RequestMapping  
  32.     public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  33.         HttpSession session = request.getSession();  
  34.         String code = (String)session.getAttribute(Constants.KAPTCHA_SESSION_KEY);  
  35.         System.out.println("******************验证码是: " + code + "******************");  
  36.           
  37.         response.setDateHeader("Expires"0);  
  38.           
  39.         // Set standard HTTP/1.1 no-cache headers.  
  40.         response.setHeader("Cache-Control""no-store, no-cache, must-revalidate");  
  41.           
  42.         // Set IE extended HTTP/1.1 no-cache headers (use addHeader).  
  43.         response.addHeader("Cache-Control""post-check=0, pre-check=0");  
  44.           
  45.         // Set standard HTTP/1.0 no-cache header.  
  46.         response.setHeader("Pragma""no-cache");  
  47.           
  48.         // return a jpeg  
  49.         response.setContentType("image/jpeg");  
  50.           
  51.         // create the text for the image  
  52.         String capText = captchaProducer.createText();  
  53.           
  54.         // store the text in the session  
  55.         session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);  
  56.           
  57.         // create the image with the text  
  58.         BufferedImage bi = captchaProducer.createImage(capText);  
  59.         ServletOutputStream out = response.getOutputStream();  
  60.           
  61.         // write the data out  
  62.         ImageIO.write(bi, "jpg", out);  
  63.         try {  
  64.             out.flush();  
  65.         } finally {  
  66.             out.close();  
  67.         }  
  68.         return null;  
  69.     }  
  70.   
  71. }  

3. JSP代码
[html]  view plain copy
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <script type="text/javascript" src="js/jquery.js"></script>  
  8. <script type="text/javascript" src="js/functions.js"></script>  
  9.   
  10.   
  11. <title>测试页面</title>  
  12. <script type="text/javascript">  
  13. $(function(){         
  14.     $('#kaptchaImage').click(function () {//生成验证码  
  15.      $(this).hide().attr('src', './kaptcha/getKaptchaImage.do?' + Math.floor(Math.random()*100) ).fadeIn();  
  16.      event.cancelBubble=true;  
  17.     });  
  18. });   
  19.   
  20.   
  21. window.onbeforeunload = function(){  
  22.     //关闭窗口时自动退出  
  23.     if(event.clientX>360&&event.clientY<0||event.altKey){     
  24.         alert(parent.document.location);  
  25.     }  
  26. };  
  27.   
  28.   
  29. function changeCode() {  
  30.     $('#kaptchaImage').hide().attr('src', './kaptcha/getKaptchaImage.do?' + Math.floor(Math.random()*100) ).fadeIn();  
  31.     event.cancelBubble=true;  
  32. }  
  33. </script>  
  34. </head>  
  35. <body>  
  36.           
  37. <div class="chknumber">  
  38.       <label>验证码:  
  39.       <input name="kaptcha" type="text" id="kaptcha" maxlength="4" class="chknumber_input" />               
  40.       </label>  
  41.       <br />  
  42.       <img src="./kaptcha/getKaptchaImage.do" id="kaptchaImage"  style="margin-bottom: -3px"/>  
  43.       <a href="#" onclick="changeCode()">看不清?换一张</a>  
  44. </div>  
  45. </body>  
  46. </html>  

4.controller中取得校验码
[java]  view plain copy
 
  1. String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);  

5.kaptcha可配置项
[plain]  view plain copy
 
  1. kaptcha.border  是否有边框  默认为true  我们可以自己设置yes,no  
  2. kaptcha.border.color   边框颜色   默认为Color.BLACK  
  3. kaptcha.border.thickness  边框粗细度  默认为1  
  4. kaptcha.producer.impl   验证码生成器  默认为DefaultKaptcha  
  5. kaptcha.textproducer.impl   验证码文本生成器  默认为DefaultTextCreator  
  6. kaptcha.textproducer.char.string   验证码文本字符内容范围  默认为abcde2345678gfynmnpwx  
  7. kaptcha.textproducer.char.length   验证码文本字符长度  默认为5  
  8. kaptcha.textproducer.font.names    验证码文本字体样式  默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)  
  9. kaptcha.textproducer.font.size   验证码文本字符大小  默认为40  
  10. kaptcha.textproducer.font.color  验证码文本字符颜色  默认为Color.BLACK  
  11. kaptcha.textproducer.char.space  验证码文本字符间距  默认为2  
  12. kaptcha.noise.impl    验证码噪点生成对象  默认为DefaultNoise  
  13. kaptcha.noise.color   验证码噪点颜色   默认为Color.BLACK  
  14. kaptcha.obscurificator.impl   验证码样式引擎  默认为WaterRipple  
  15. kaptcha.word.impl   验证码文本字符渲染   默认为DefaultWordRenderer  
  16. kaptcha.background.impl   验证码背景生成器   默认为DefaultBackground  
  17. kaptcha.background.clear.from   验证码背景颜色渐进   默认为Color.LIGHT_GRAY  
  18. kaptcha.background.clear.to   验证码背景颜色渐进   默认为Color.WHITE  
  19. kaptcha.image.width   验证码图片宽度  默认为200  
  20. kaptcha.image.height  验证码图片高度  默认为50   

猜你喜欢

转载自luanxiyuan.iteye.com/blog/2000406