Kaptcha 和 JCaptcha 使用介绍和实例

LeilaniHodg 8年前
   <p>Kaptcha 是一个非常实用的验证码生成工具,它是基于SimpleCaptcha的开源项目。通过调整Kaptcha配置可以生成各种样式的验证码。</p>    <p>使用Kaptcha可以方便的配置以下细节:</p>    <ul>     <li>验证码的字体</li>     <li>验证码字体的大小</li>     <li>验证码字体的字体颜色</li>     <li>验证码内容的范围</li>     <li>验证码图片的大小,边框,边框粗细,边框颜色</li>     <li>验证码的干扰线</li>     <li>验证码的样式</li>    </ul>    <h3><strong>JCaptcha简介</strong></h3>    <p>JCapthca是一个开源的用来生成图形验证码的Java开源组件,它非常强大,不光是可以生成图片式的验证码,还可以生成声音式的。</p>    <p>JCaptcha是CAPTCHA里面的一个比较著名的项目。</p>    <h3><strong>Kaptcha测试实例</strong></h3>    <p>添加依赖包</p>    <p>在pom.xml文件中新增dependency</p>    <pre>  <code class="language-java"><dependency>  <groupId>com.google.code.kaptcha</groupId>  <artifactId>kaptcha</artifactId>  <version>2.3</version>  </dependency>  </code></pre>    <p>配置applicationContext.xml</p>    <pre>  <code class="language-java"><beanid="captchaProducer"class="com.google.code.kaptcha.impl.DefaultKaptcha">  <propertyname="config">  <beanclass="com.google.code.kaptcha.util.Config">  <constructor-arg>  <props>  <propkey="kaptcha.border">yes</prop>  <propkey="kaptcha.border.color">105,179,90</prop>  <propkey="kaptcha.textproducer.font.color">blue</prop>  <propkey="kaptcha.image.width">80</prop>  <propkey="kaptcha.image.height">30</prop>  <propkey="kaptcha.textproducer.font.size">27</prop>  <propkey="kaptcha.session.key">code</prop>  <propkey="kaptcha.textproducer.char.length">4</prop>  <propkey="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>  <propkey="kaptcha.textproducer.char.string">123456789ABCE</prop>  <propkey="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>  <propkey="kaptcha.noise.color">white</prop>  <propkey="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>  <propkey="kaptcha.background.clear.from">white</prop>  <propkey="kaptcha.background.clear.to">white</prop>  </props>  </constructor-arg>  </bean>  </property>  </bean>  </code></pre>    <p><strong>Controller实现</strong></p>    <pre>  <code class="language-java">importcom.google.code.kaptcha.Constants;  importcom.google.code.kaptcha.Producer;  importorg.springframework.stereotype.Controller;  importorg.springframework.web.bind.annotation.RequestMapping;  importorg.springframework.web.bind.annotation.ResponseBody;    importjavax.annotation.Resource;  importjavax.imageio.ImageIO;  importjavax.servlet.ServletOutputStream;  importjavax.servlet.http.Cookie;  importjavax.servlet.http.HttpServletRequest;  importjavax.servlet.http.HttpServletResponse;  importjava.awt.image.BufferedImage;  importjava.util.Random;    @Controller  @RequestMapping("/code")  publicclassCaptchaController{    @Resource  privateProducer captchaProducer;    @ResponseBody  @RequestMapping(value ="/captchaImage")  publicvoidgetKaptchaImage(HttpServletRequest request,HttpServletResponse response)throwsException{   response.setDateHeader("Expires",0);   response.setHeader("Cache-Control","no-cache, must-revalidate");   response.addHeader("Cache-Control","post-check=0, pre-check=0");   response.setHeader("Pragma","no-cache");   response.setContentType("image/jpeg");     String capText = captchaProducer.createText();// 生成验证码字符串     Cookie cookie = newCookie(Constants.KAPTCHA_SESSION_KEY, capText);// 生成cookie   cookie.setMaxAge(300);// 300秒生存期     response.addCookie(cookie); // 将cookie加入response     BufferedImage bi = captchaProducer.createImage(capText);// 生成验证码图片   ServletOutputStream out = response.getOutputStream();   ImageIO.write(bi, "jpg", out);  try{   out.flush();   } finally{   out.close();   }    return;   }    privateStringgetRandomString(intlength){   String base = "abcdefghijklmnopqrstuvwxyz0123456789";   Random random = newRandom();   StringBuilder sb = newStringBuilder(length +1);  for(inti =0; i < length; ++i) {  intnumber = random.nextInt(base.length());   sb.append(base.charAt(number));   }  returnsb.toString();   }  }  </code></pre>    <p><strong>前端代码</strong></p>    <pre>  <code class="language-java"><imgid="verify"width="80"height="30"src="/code/captchaImage"/>  </code></pre>    <p><strong>测试结果</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/23d6cd7ef4b8cd3b67eaf7788d623077.png"></p>    <p><strong>Kaptcha可配置项</strong></p>    <table>     <thead>      <tr>       <th>配置项</th>       <th>描述</th>       <th>默认值</th>       <th>可选值</th>      </tr>     </thead>     <tbody>      <tr>       <td>kaptcha.border</td>       <td>是否有边框</td>       <td>默认为yes</td>       <td>yes,no</td>      </tr>      <tr>       <td>kaptcha.border.color</td>       <td>边框颜色</td>       <td>默认为Color.BLACK</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.border.thickness</td>       <td>边框粗细度</td>       <td>默认为1</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.producer.impl</td>       <td>验证码生成器</td>       <td>默认为DefaultKaptcha</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.textproducer.impl</td>       <td>验证码文本生成器</td>       <td>默认为DefaultTextCreator</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.textproducer.char.string</td>       <td>验证码文本字符内容范围</td>       <td> </td>       <td> </td>      </tr>      <tr>       <td>kaptcha.textproducer.char.length</td>       <td>验证码文本字符长度</td>       <td>默认为5</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.textproducer.font.names</td>       <td>验证码文本字体样式</td>       <td> </td>       <td> </td>      </tr>      <tr>       <td>kaptcha.textproducer.font.size</td>       <td>验证码文本字符大小</td>       <td>默认为40</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.textproducer.font.color</td>       <td>验证码文本字符颜色</td>       <td>默认为Color.BLACK</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.textproducer.char.space</td>       <td>验证码文本字符间距</td>       <td>默认为2</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.noise.impl</td>       <td>验证码噪点生成对象</td>       <td>默认为DefaultNoise</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.noise.color</td>       <td>验证码噪点颜色</td>       <td>默认为Color.BLACK</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.obscurificator.impl</td>       <td>验证码样式引擎</td>       <td>默认为WaterRipple</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.word.impl</td>       <td>验证码文本字符渲染</td>       <td>默认为DefaultWordRenderer</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.background.impl</td>       <td>验证码背景生成器</td>       <td>默认为DefaultBackground</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.background.clear.from</td>       <td>验证码背景颜色渐进</td>       <td>默认为Color.LIGHT_GRAY</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.background.clear.to</td>       <td>验证码背景颜色渐进</td>       <td>默认为Color.WHITE</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.image.width</td>       <td>验证码图片宽度</td>       <td>默认为200</td>       <td> </td>      </tr>      <tr>       <td>kaptcha.image.height</td>       <td>验证码图片高度</td>       <td>默认为50</td>      </tr>     </tbody>    </table>    <p>图片样式:</p>    <p>水纹 com.google.code.kaptcha.impl.WaterRipple</p>    <p>鱼眼 com.google.code.kaptcha.impl.FishEyeGimpy</p>    <p>阴影 com.google.code.kaptcha.impl.ShadowGimpy</p>    <h3><strong>JCaptcha测试实例</strong></h3>    <p><strong>添加依赖包</strong></p>    <pre>  <code class="language-java"><dependency>  <groupId>com.octo.captcha</groupId>  <artifactId>jcaptcha-all</artifactId>  <version>1.0-RC6</version>  <exclusions>  <exclusion>  <groupId>org.springframework</groupId>  <artifactId>spring</artifactId>  </exclusion>  </exclusions>  </dependency>  <dependency>  <groupId>commons-logging</groupId>  <artifactId>commons-logging</artifactId>  <version>1.2</version>  </dependency>  <dependency>  <groupId>commons-collections</groupId>  <artifactId>commons-collections</artifactId>  <version>3.2.2</version>  </dependency>  </code></pre>    <p>注意:如果是Spring项目,必须加上exclusion,不然会提示BeanDefinitionParsingException错误。</p>    <p>org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate NamespaceHandler for namespace </p>    <p><strong>Service实现</strong></p>    <p>JCaptcha建议使用单例提供服务。</p>    <pre>  <code class="language-java">importcom.octo.captcha.component.image.backgroundgenerator.GradientBackgroundGenerator;  importcom.octo.captcha.component.image.color.SingleColorGenerator;  importcom.octo.captcha.component.image.fontgenerator.RandomFontGenerator;  importcom.octo.captcha.component.image.textpaster.NonLinearTextPaster;  importcom.octo.captcha.component.image.wordtoimage.ComposedWordToImage;  importcom.octo.captcha.component.word.wordgenerator.RandomWordGenerator;  importcom.octo.captcha.engine.GenericCaptchaEngine;  importcom.octo.captcha.image.gimpy.GimpyFactory;  importcom.octo.captcha.service.captchastore.FastHashMapCaptchaStore;  importcom.octo.captcha.service.image.DefaultManageableImageCaptchaService;  importcom.octo.captcha.service.image.ImageCaptchaService;    importjava.awt.*;    publicclassCaptchaService{  privatestaticclassSingletonHolder{  privatestaticImageCaptchaService imageCaptchaService =newDefaultManageableImageCaptchaService(  newFastHashMapCaptchaStore(),  newGenericCaptchaEngine(  newGimpyFactory[]{newGimpyFactory(  newRandomWordGenerator("123456789ABCE"),  newComposedWordToImage(  newRandomFontGenerator(20,20,newFont[]{newFont("Arial",20,20)}),  newGradientBackgroundGenerator(90,30,newSingleColorGenerator(newColor(235,255,255)),newSingleColorGenerator(newColor(255,195,230))),  newNonLinearTextPaster(4,4,newColor(11,11,11))   )   )}   ),  180,  180000,  20000   );   }  privateCaptchaService(){}  publicstaticImageCaptchaServicegetInstance(){  returnSingletonHolder.imageCaptchaService;   }  }  </code></pre>    <p><strong>Controller实现</strong></p>    <pre>  <code class="language-java">importorg.springframework.stereotype.Controller;  importorg.springframework.web.bind.annotation.RequestMapping;  importorg.springframework.web.bind.annotation.ResponseBody;    importjavax.imageio.ImageIO;  importjavax.servlet.ServletOutputStream;  importjavax.servlet.http.HttpServletRequest;  importjavax.servlet.http.HttpServletResponse;  importjava.awt.image.BufferedImage;    @Controller  @RequestMapping("/code")  publicclassCaptchaController{    @ResponseBody  @RequestMapping(value ="/captchaImage")  publicvoidgetJCaptchaImage(HttpServletRequest request,HttpServletResponse response)throwsException{   response.setDateHeader("Expires",0);   response.setHeader("Cache-Control","no-cache, must-revalidate");   response.addHeader("Cache-Control","post-check=0, pre-check=0");   response.setHeader("Pragma","no-cache");   response.setContentType("image/jpeg");   BufferedImage bi = CaptchaService.getInstance().getImageChallengeForID(request.getSession(true)   .getId());   ServletOutputStream out = response.getOutputStream();   ImageIO.write(bi, "jpg", out);  try{   out.flush();   } finally{   out.close();   }  return;   }    @ResponseBody  @RequestMapping(value ="/validate")  publicBooleanlogin(String username, String password, String captcha, HttpServletRequest request){   Boolean result = false;   Boolean isCaptchaCorrect = CaptchaService.getInstance().validateResponseForID(request.getSession().getId(), captcha);  if(isCaptchaCorrect) {     }  returnresult;   }  }  </code></pre>    <p><strong>前端代码</strong></p>    <pre>  <code class="language-java"><img id="verify" width="80" height="30" src="/code/captchaImage" />  </code></pre>    <p>测试结果</p>    <p><a href="https://simg.open-open.com/show/dff0dc2d61187d70b107071aa8ec2d6d.png" rel="group"><img alt="Kaptcha 和 JCaptcha 使用介绍和实例" src="https://simg.open-open.com/show/dff0dc2d61187d70b107071aa8ec2d6d.png" width="192" height="80"></a></p>    <p>来自:http://tedhacker.top/2016/11/14/Kaptcha和JCaptcha使用介绍/</p>    <p> </p>