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. <span style="font-size:18px;">    <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></span>  
2. Controller的實現
[java] view plain copy
  1. <span style="font-size:18px;">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. }  
  72. </span>  

3. JSP代碼
[html] view plain copy
  1. <span style="font-size:18px;"><%@ 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>  
  47. </span>  

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. <span style="font-size:12px;">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   
  21. </span>  
發佈了28 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章