1. 程式人生 > >kaptcha 驗證碼在spring mvc 中的使用

kaptcha 驗證碼在spring mvc 中的使用

kaptcha 是一個非常實用的驗證碼生成工具。有了它,你可以生成各種樣式的驗證碼,因為它是可配置的。kaptcha工作的原理是呼叫 com.google.code.kaptcha.servlet.KaptchaServlet,生成一個圖片。同時將生成的驗證碼字串放到 HttpSession中。

使用kaptcha可以方便的配置:

  • 驗證碼的字型
  • 驗證碼字型的大小
  • 驗證碼字型的字型顏色
  • 驗證碼內容的範圍(數字,字母,中文漢字!)
  • 驗證碼圖片的大小,邊框,邊框粗細,邊框顏色
  • 驗證碼的干擾線(可以自己繼承com.google.code.kaptcha.NoiseProducer寫一個自定義的干擾線)
  • 驗證碼的樣式(魚眼樣式、3D、普通模糊……當然也可以繼承com.google.code.kaptcha.GimpyEngine自定義樣式)

……

詳細資訊請看下面的web.xml檔案

下面介紹一下用法:

3.配置web.xml檔案

Xml程式碼  收藏程式碼
  1. <!--Kaptcha 驗證碼  --><!--  
  2.     < servlet >   
  3.         < servlet-name > kaptcha</ servlet-name >   
  4.         < servlet-class > com.google.code.kaptcha.servlet.KaptchaServlet</
    servlet-class >   
  5.         < init-param >   
  6.             < param-name > kaptcha.border</ param-name >   
  7.             < param-value > no</ param-value >   
  8.         </ init-param >   
  9.         < init-param >   
  10.             < param-name > kaptcha.border.color</
    param-name >   
  11.             < param-value > 105,179,90</ param-value >   
  12.         </ init-param >        
  13.         < init-param >   
  14.             < param-name > kaptcha.textproducer.font.color</ param-name >   
  15.             < param-value > red</ param-value >   
  16.         </ init-param >   
  17.         < init-param >   
  18.             < param-name > kaptcha.image.width</ param-name >   
  19.             < param-value > 250</ param-value >   
  20.         </ init-param >   
  21.         < init-param >   
  22.             < param-name > kaptcha.image.height</ param-name >   
  23.             < param-value > 90</ param-value >   
  24.         </ init-param >   
  25.         < init-param >   
  26.             < param-name > kaptcha.textproducer.font.size</ param-name >   
  27.             < param-value > 70</ param-value >   
  28.         </ init-param >   
  29.         < init-param >   
  30.             < param-name > kaptcha.session.key</ param-name >   
  31.             < param-value > code</ param-value >   
  32.         </ init-param >   
  33.         < init-param >   
  34.             < param-name > kaptcha.textproducer.char.length</ param-name >   
  35.             < param-value > 4</ param-value >   
  36.         </ init-param >   
  37.         < init-param >   
  38.             < param-name > kaptcha.textproducer.font.names</ param-name >   
  39.             < param-value > 宋體,楷體,微軟雅黑</ param-value >   
  40.         </ init-param >        
  41.     </ servlet >   
Xml程式碼 Xml程式碼  收藏程式碼
  1.     < servlet-mapping >   
  2. < servlet-name > kaptcha</ servlet-name >   
  3. < url-pattern > /ClinicCountManager/kaptcha.jpg</ url-pattern >   
  4. lt;/servlet-mapping>   

jsp 頁面使用

Java程式碼  收藏程式碼
  1. <table>  
  2.         <tr>  
  3.             <td><img src="/ClinicCountManager/kaptcha.jpg"></td>  
  4.             <td valign="top">  
  5.                 <form method="POST">  
  6.                     <br>sec code:<input type="text" name="kaptchafield"><br />  
  7.                     <input type="submit" name="submit">  
  8.                 </form>  
  9.             </td>  
  10.         </tr>  
  11.     </table>    
  12.     <br /><br /><br /><br />  
  13.     <%  
  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("<b>true</b>");  
  20.             } else  {  
  21.                 out.println("<b>false</b>");  
  22.             }  
  23.     %>  

上面的配置在普通jsp環境下面是有效的,如果在spring mvc環境下,則取不到session值,對於sping mvc環境驗證碼配置如下:

1.不用在web.xml進行相關配置,在applicationContext.xml中配置

Xml程式碼  Xml程式碼  收藏程式碼
  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" > no</ prop >   
  7.                         < prop  key ="kaptcha.border.color" > 105,179,90</ prop >   
  8.                         < prop  key ="kaptcha.textproducer.font.color" > red</ prop >   
  9.                         < prop  key ="kaptcha.image.width" > 250</ prop >   
  10.                         < prop  key ="kaptcha.textproducer.font.size" > 90</ prop >   
  11.                         < prop  key ="kaptcha.image.height" > 90</ 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 >   

新建生成圖片控制類

Java程式碼  收藏程式碼
  1. import  java.awt.image.BufferedImage;  
  2. import  javax.imageio.ImageIO;  
  3. import  javax.servlet.ServletOutputStream;  
  4. import  javax.servlet.http.HttpServletRequest;  
  5. import  javax.servlet.http.HttpServletResponse;  
  6. import  org.springframework.beans.factory.annotation.Autowired;  
  7. import  org.springframework.stereotype.Controller;  
  8. import  org.springframework.web.bind.annotation.RequestMapping;  
  9. 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程式碼  收藏程式碼
  1. <div class ="chknumber">  
  2.        <label>驗證碼:          
  3.        <input name="kaptcha" type="text" id="kaptcha" maxlength="4" class ="chknumber_input" />               
  4.        </label>  
  5.         <img src="/ClinicCountManager/captcha-image.do" width="55" height="20" id="kaptchaImage"  style="margin-bottom: -3px"/>   
  6.        <script type="text/javascript">      
  7.         $(function(){           
  8.             $('#kaptchaImage').click(function () {//生成驗證碼  
  9.              $(this ).hide().attr('src', '/ClinicCountManager/captcha-image.do?' + Math.floor(Math.random()*100 ) ).fadeIn(); })      
  10.                   });   
  11.        </script>   
  12.      </div>  

 取驗證碼的方式

Java程式碼 Java程式碼  收藏程式碼
  1. String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);