jcaptcha验证码学习

原文->http://wwwzhouhui.iteye.com/blog/410935

现在项目中用SPRING 比较多所以整合了一下。其中的部分代码是参考一个jeecms项目的,讲其中的jcaptcha验证码这块剥离出来。 
  项目在上篇基础上编写的,部分代码是上篇中的代码(偷懒了) 
1.用到得JAR 
   commons-logging.jar,jcaptcha-all-1.0-RC6.jar,spring-beans-2.5.6.jar 
   spring-context-2.5.6.jar,spring-core-2.5.6.jar,spring-web-2.5.6.jar 
2.applicationContext.xml 

Xml代码   收藏代码
  1.  <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"  
  6.     >  
  7.     <!--验证码生成器-->  
  8.     <bean id="imageCaptchaService" class="com.spring.CaptchaService">  
  9.         <constructor-arg type="com.octo.captcha.service.captchastore.CaptchaStore" index="0">  
  10.             <ref bean="fastHashMapCaptchaStore"/>  
  11.         </constructor-arg>     
  12.         <!--which captcha Engine you use-->     
  13.         <constructor-arg type="com.octo.captcha.engine.CaptchaEngine" index="1">  
  14.             <ref bean="captchaEngineEx"/>  
  15.         </constructor-arg>     
  16.         <constructor-arg index="2">     
  17.             <value>180</value>     
  18.         </constructor-arg>     
  19.         <constructor-arg index="3">     
  20.             <value>100000</value>     
  21.         </constructor-arg>     
  22.         <constructor-arg index="4">     
  23.             <value>75000</value>     
  24.         </constructor-arg>    
  25.     </bean>  
  26.     <bean id="fastHashMapCaptchaStore" class="com.octo.captcha.service.captchastore.FastHashMapCaptchaStore"/>     
  27.     <!--you can define more than one captcha engine here -->     
  28.     <bean id="captchaEngineEx" class="com.spring.CaptchaEngineEx"/>    
  29. </beans>  


3. web.xml 

Xml代码   收藏代码
  1.  <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4"   
  3.     xmlns="http://java.sun.com/xml/ns/j2ee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  7.     <context-param>  
  8.         <param-name>contextConfigLocation</param-name>  
  9.         <param-value>  
  10.             classpath:applicationContext.xml  
  11.         </param-value>  
  12.     </context-param>  
  13.     <listener>  
  14.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  15.     </listener>  
  16.     <!--    
  17.     <servlet>    
  18.         <servlet-name>jcaptcha</servlet-name>    
  19.         <servlet-class>com.code.ImageCaptchaServlet</servlet-class>    
  20.         <load-on-startup>0</load-on-startup>    
  21.     </servlet>    
  22.     <servlet-mapping>    
  23.         <servlet-name>jcaptcha</servlet-name>    
  24.         <url-pattern>/jcaptcha</url-pattern>    
  25.     </servlet-mapping>  
  26.     -->  
  27.       
  28.     <servlet>    
  29.         <servlet-name>jcaptcha2</servlet-name>    
  30.         <servlet-class>com.spring.ImageCaptchaServlet</servlet-class>    
  31.         <load-on-startup>0</load-on-startup>    
  32.     </servlet>    
  33.     <servlet-mapping>    
  34.         <servlet-name>jcaptcha2</servlet-name>    
  35.         <url-pattern>/jcaptcha</url-pattern>    
  36.     </servlet-mapping>    
  37.     <!--  
  38.     <servlet>    
  39.         <servlet-name>checkjcaptcha</servlet-name>    
  40.         <servlet-class>com.code.ValidationServlet</servlet-class>    
  41.         <load-on-startup>1</load-on-startup>    
  42.     </servlet>    
  43.     <servlet-mapping>    
  44.         <servlet-name>checkjcaptcha</servlet-name>    
  45.         <url-pattern>/validateAction</url-pattern>    
  46.     </servlet-mapping>  
  47.     -->  
  48.     <servlet>    
  49.         <servlet-name>checkjcaptcha2</servlet-name>    
  50.         <servlet-class>com.spring.ValidationServlet</servlet-class>    
  51.         <load-on-startup>1</load-on-startup>    
  52.     </servlet>    
  53.     <servlet-mapping>    
  54.         <servlet-name>checkjcaptcha2</servlet-name>    
  55.         <url-pattern>/validateAction</url-pattern>    
  56.     </servlet-mapping>  
  57.       
  58.   <welcome-file-list>  
  59.     <welcome-file>index.jsp</welcome-file>  
  60.   </welcome-file-list>  
  61. </web-app>  


4.java 代码 
   自定义生成代码部分 
   CaptchaEngineEx.java 
 

Java代码   收藏代码
  1. package com.spring;  
  2.   
  3. import java.awt.Color;  
  4.   
  5. import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;  
  6. import com.octo.captcha.component.image.backgroundgenerator.GradientBackgroundGenerator;  
  7. import com.octo.captcha.component.image.color.SingleColorGenerator;  
  8. import com.octo.captcha.component.image.fontgenerator.FontGenerator;  
  9. import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;  
  10. import com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster;  
  11. import com.octo.captcha.component.image.textpaster.TextPaster;  
  12. import com.octo.captcha.component.image.textpaster.textdecorator.BaffleTextDecorator;  
  13. import com.octo.captcha.component.image.textpaster.textdecorator.LineTextDecorator;  
  14. import com.octo.captcha.component.image.textpaster.textdecorator.TextDecorator;  
  15. import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;  
  16. import com.octo.captcha.component.image.wordtoimage.WordToImage;  
  17. import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;  
  18. import com.octo.captcha.component.word.wordgenerator.WordGenerator;  
  19. import com.octo.captcha.engine.image.ListImageCaptchaEngine;  
  20. import com.octo.captcha.image.gimpy.GimpyFactory;  
  21.   
  22. /***********************************************************************    
  23.  *    
  24.  *   CaptchaEngineEx.java      
  25.  *   @copyright       Copyright:   2009-2012      
  26.  *   @creator         周辉<br/>    
  27.  *   @create-time   Jun 18, 2009   2:41:12 PM    
  28.  *   @revision         $Id:     *    
  29.  ***********************************************************************/  
  30. public class CaptchaEngineEx extends ListImageCaptchaEngine {  
  31.   
  32.     protected void buildInitialFactories() {  
  33.         // Set Captcha Word Length Limitation which should not over 6  
  34.         Integer minAcceptedWordLength = new Integer(4);  
  35.         Integer maxAcceptedWordLength = new Integer(5);  
  36.         // Set up Captcha Image Size: Height and Width  
  37.         Integer imageHeight = new Integer(40);  
  38.         Integer imageWidth = new Integer(100);  
  39.   
  40.         // Set Captcha Font Size  
  41.         Integer minFontSize = new Integer(20);  
  42.         Integer maxFontSize = new Integer(22);  
  43.         // We just generate digit for captcha source char Although you can use  
  44.         // abcdefghijklmnopqrstuvwxyz  
  45.         WordGenerator wordGenerator = new RandomWordGenerator("0123456789");  
  46.   
  47.         // cyt and unruledboy proved that backgroup not a factor of Security. A  
  48.         // captcha attacker won't affaid colorful backgroud, so we just use  
  49.         // white  
  50.         // color, like google and hotmail.  
  51.         BackgroundGenerator backgroundGenerator = new GradientBackgroundGenerator(  
  52.                 imageWidth, imageHeight, Color.white, Color.white);  
  53.   
  54.         // font is not helpful for security but it really increase difficultness  
  55.         // for  
  56.         // attacker  
  57.         FontGenerator fontGenerator = new RandomFontGenerator(minFontSize,  
  58.                 maxFontSize);  
  59.         // Note that our captcha color is Blue  
  60.         SingleColorGenerator scg = new SingleColorGenerator(Color.blue);  
  61.   
  62.         // decorator is very useful pretend captcha attack. we use two line text  
  63.         // decorators.  
  64.   
  65.         LineTextDecorator lineDecorator = new LineTextDecorator(1, Color.blue);  
  66.         // LineTextDecorator line_decorator2 = new LineTextDecorator(1,  
  67.         // Color.blue);  
  68.         TextDecorator[] textdecorators = new TextDecorator[1];  
  69.   
  70.         textdecorators[0] = lineDecorator;  
  71.         // textdecorators[1] = line_decorator2;  
  72.   
  73.         TextPaster textPaster = new DecoratedRandomTextPaster(  
  74.                 minAcceptedWordLength, maxAcceptedWordLength, scg,  
  75.                 new TextDecorator[] { new BaffleTextDecorator(new Integer(1),  
  76.                         Color.white) });  
  77.   
  78.         // ok, generate the WordToImage Object for logon service to use.  
  79.         WordToImage wordToImage = new ComposedWordToImage(fontGenerator,  
  80.                 backgroundGenerator, textPaster);  
  81.         addFactory(new GimpyFactory(wordGenerator, wordToImage));  
  82.   
  83.     }  
  84.   
  85. }  


生成图片的servlet 
ImageCaptchaServlet.JAVA 

Java代码   收藏代码
  1. package com.spring;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6.   
  7. import javax.servlet.ServletConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletOutputStream;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.springframework.web.context.WebApplicationContext;  
  15. import org.springframework.web.context.support.WebApplicationContextUtils;  
  16.   
  17. import com.octo.captcha.service.CaptchaServiceException;  
  18. import com.octo.captcha.service.image.ImageCaptchaService;  
  19. import com.sun.image.codec.jpeg.JPEGCodec;  
  20. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  21.   
  22. /***********************************************************************    
  23.  *    
  24.  *   ImageCaptchaServlet.java      
  25.  *   @copyright       Copyright:   2009-2012      
  26.  *   @creator         周辉<br/>    
  27.  *   @create-time   Jun 18, 2009   2:44:15 PM    
  28.  *   @revision         $Id:     *    
  29.  ***********************************************************************/  
  30. @SuppressWarnings("serial")  
  31. public class ImageCaptchaServlet extends HttpServlet {  
  32.     private ImageCaptchaService imageCaptchaService;  
  33.     private String beanName = "imageCaptchaService";  
  34.   
  35.     public void init(ServletConfig servletConfig) throws ServletException {  
  36.         super.init(servletConfig);  
  37.         WebApplicationContext wac = WebApplicationContextUtils  
  38.                 .getRequiredWebApplicationContext(servletConfig  
  39.                         .getServletContext());  
  40.         imageCaptchaService = (ImageCaptchaService) wac.getBean(beanName,  
  41.                 ImageCaptchaService.class);  
  42.     }  
  43.   
  44.     protected void doGet(HttpServletRequest httpServletRequest,  
  45.             HttpServletResponse httpServletResponse) throws ServletException,  
  46.             IOException {  
  47.   
  48.         byte[] captchaChallengeAsJpeg = null;  
  49.         // the output stream to render the captcha image as jpeg into  
  50.         ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();  
  51.         try {  
  52.             // get the session id that will identify the generated captcha.  
  53.             // the same id must be used to validate the response, the session id  
  54.             // is a good candidate!  
  55.             String captchaId = httpServletRequest.getSession().getId();  
  56.             // call the ImageCaptchaService getChallenge method  
  57.             BufferedImage challenge = imageCaptchaService  
  58.                     .getImageChallengeForID(captchaId, httpServletRequest  
  59.                             .getLocale());  
  60.   
  61.             // a jpeg encoder  
  62.             JPEGImageEncoder jpegEncoder = JPEGCodec  
  63.                     .createJPEGEncoder(jpegOutputStream);  
  64.             jpegEncoder.encode(challenge);  
  65.         } catch (IllegalArgumentException e) {  
  66.             httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);  
  67.             return;  
  68.         } catch (CaptchaServiceException e) {  
  69.             httpServletResponse  
  70.                     .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);  
  71.             return;  
  72.         }  
  73.   
  74.         captchaChallengeAsJpeg = jpegOutputStream.toByteArray();  
  75.   
  76.         // flush it in the response  
  77.         httpServletResponse.setHeader("Cache-Control""no-store");  
  78.         httpServletResponse.setHeader("Pragma""no-cache");  
  79.         httpServletResponse.setDateHeader("Expires"0);  
  80.         httpServletResponse.setContentType("image/jpeg");  
  81.         ServletOutputStream responseOutputStream = httpServletResponse  
  82.                 .getOutputStream();  
  83.         responseOutputStream.write(captchaChallengeAsJpeg);  
  84.         responseOutputStream.flush();  
  85.         responseOutputStream.close();  
  86.     }  
  87. }  


验证的单列类 CaptchaService.java 

Java代码   收藏代码
  1. package com.spring;  
  2.   
  3. import com.octo.captcha.engine.CaptchaEngine;  
  4. import com.octo.captcha.service.captchastore.CaptchaStore;  
  5. import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;  
  6.   
  7. /***********************************************************************    
  8.  *    
  9.  *   CaptchaService.java      
  10.  *   @copyright       Copyright:   2009-2012      
  11.  *   @creator         周辉<br/>    
  12.  *   @create-time   Jun 18, 2009   2:42:53 PM    
  13.  *   @revision         $Id:     *    
  14.  ***********************************************************************/  
  15. public class CaptchaService extends DefaultManageableImageCaptchaService {  
  16.     public CaptchaService() {  
  17.         super();  
  18.     }  
  19.   
  20.     public CaptchaService(int minSeconds, int maxStoreSize, int loadBefore) {  
  21.         super(minSeconds, maxStoreSize, loadBefore);  
  22.     }  
  23.   
  24.     public CaptchaService(CaptchaStore captchaStore,  
  25.             CaptchaEngine captchaEngine, int minSeconds, int maxStoreSize,  
  26.             int loadBefore) {  
  27.         super(captchaStore, captchaEngine, minSeconds, maxStoreSize, loadBefore);  
  28.     }  
  29.   
  30.     public Boolean validateResponseForID(String ID, Object response) {  
  31.         Boolean isHuman;  
  32.         try {  
  33.             isHuman = super.validateResponseForID(ID, response);  
  34.         } catch (Exception e) {  
  35.             isHuman = false;  
  36.         }  
  37.         return isHuman;  
  38.     }  
  39. }  


最后测试验证的类 
ValidationServlet.java 

Java代码   收藏代码
  1. package com.spring;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.ServletConfig;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.springframework.web.context.WebApplicationContext;  
  12. import org.springframework.web.context.support.WebApplicationContextUtils;  
  13.   
  14. import com.octo.captcha.service.CaptchaServiceException;  
  15. import com.octo.captcha.service.image.ImageCaptchaService;  
  16.   
  17. /***********************************************************************    
  18.  *    
  19.  *   ValidationServlet.java      
  20.  *   @copyright       Copyright:   2009-2012      
  21.  *   @creator         周辉<br/>    
  22.  *   @create-time   Jun 18, 2009   3:16:50 PM    
  23.  *   @revision         $Id:     *    
  24.  ***********************************************************************/  
  25. public class ValidationServlet extends HttpServlet {  
  26.     private ImageCaptchaService imageCaptchaService;  
  27.     private String beanName = "imageCaptchaService";  
  28.     public void init(ServletConfig servletConfig) throws ServletException {     
  29.         super.init(servletConfig);     
  30.         WebApplicationContext wac = WebApplicationContextUtils  
  31.         .getRequiredWebApplicationContext(servletConfig  
  32.                 .getServletContext());  
  33.         imageCaptchaService = (ImageCaptchaService) wac.getBean(beanName,  
  34.                 ImageCaptchaService.class);  
  35.     }     
  36.     
  37.     protected void doGet(HttpServletRequest httpServletRequest,     
  38.             HttpServletResponse httpServletResponse) throws ServletException,     
  39.             IOException {     
  40.     
  41.         Boolean isResponseCorrect = Boolean.FALSE;     
  42.         //remenber that we need an id to validate!     
  43.         String captchaId = httpServletRequest.getSession().getId();     
  44.         //retrieve the response     
  45.         String response = httpServletRequest.getParameter("j_captcha_response");     
  46.         // Call the Service method     
  47.         try {     
  48.             isResponseCorrect=imageCaptchaService.validateResponseForID(captchaId, response);  
  49.         } catch (CaptchaServiceException e) {     
  50.             //should not happen, may be thrown if the id is not valid      
  51.         }     
  52.         System.out.println(isResponseCorrect);   
  53.        // httpServletResponse.encodeUrl("sucess.html");  
  54.         if(isResponseCorrect.booleanValue()){  
  55.             httpServletResponse.sendRedirect("success.html");  
  56.         }  
  57.         else {  
  58.              httpServletResponse.sendRedirect("failture.html");  
  59.         }  
  60.     }     
  61. }  


5 页面HTML 
  login2.html 

Html代码   收藏代码
  1. <html>    
  2.   <head>    
  3.     <title>MyHtml.html</title>    
  4.          
  5.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    
  6.     <meta http-equiv="description" content="this is my page">    
  7.     <meta http-equiv="content-type" content="text/html; charset=UTF-8">    
  8.          
  9.     <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->    
  10.     
  11.   </head>    
  12.        
  13.   <body>    
  14.     <form name="f1" id="f1" action="/jcaptcha/validateAction" method="get">    
  15.       <table border="0">    
  16.         <tr>    
  17.           <td>验证码:</td>    
  18.           <td><img src="jcaptcha"><input type='text' name='j_captcha_response' value=''></td>    
  19.         </tr>    
  20.         <tr>    
  21.           <td colspan="2" align="center"><input type="submit"></td>    
  22.         </tr>    
  23.       </table>    
  24.            
  25.     </form>    
  26.   </body>    
  27. </html>    


6 最后调用成功失败的页面success.html failture.html(略) 
最后发布程序,启动TOMCAT 输入 
http://localhost:8081/jcaptcha/login2.html 
看到生成验证码了 

猜你喜欢

转载自lpyyn.iteye.com/blog/2189296