使用jcaptcha插件生成验证码

Posted mfmdaoyou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用jcaptcha插件生成验证码相关的知识,希望对你有一定的参考价值。

1.从官网http://jcaptcha.sourceforge.net/下载插件。将对应jar包导入到lib文件夹下
技术分享
2.创建一个CaptchaServiceSingleton类用来获取jcaptcha自己实现的默认验证码生成器对象DefaultManageableImageCaptchaService(使用单例模式)。
package com.xhc.jcaptcha;

import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;

public class CaptchaServiceSingleton {
  private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();
 
     public static ImageCaptchaService getInstance(){
         return instance;
     }
}

3.创建处理验证码生成的servlet
package com.xhc.jcaptcha;

import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageCaptchaServlet extends HttpServlet {

 public void destroy() {
  super.destroy();
 }
 public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
   throws ServletException, IOException {
    byte[] captchaChallengeAsJpeg = null;
        // the output stream to render the captcha image as jpeg into
         ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
         try {
         // get the session id that will identify the generated captcha.
         //the same id must be used to validate the response, the session id is a good candidate!
         String captchaId = httpServletRequest.getSession().getId();
         // call the ImageCaptchaService getChallenge method
             BufferedImage challenge = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
                     challenge=CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,
                             httpServletRequest.getLocale());
             // a jpeg encoder
             JPEGImageEncoder jpegEncoder =
                     JPEGCodec.createJPEGEncoder(jpegOutputStream);
             jpegEncoder.encode(challenge);
         } catch (IllegalArgumentException e) {
             httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
             return;
         } catch (CaptchaServiceException e) {
             httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
             return;
         }
 
         captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
 
         // flush it in the response
         httpServletResponse.setHeader("Cache-Control", "no-store");
         httpServletResponse.setHeader("Pragma", "no-cache");
         httpServletResponse.setDateHeader("Expires", 0);
         httpServletResponse.setContentType("image/jpeg");
         ServletOutputStream responseOutputStream =
                 httpServletResponse.getOutputStream();
         responseOutputStream.write(captchaChallengeAsJpeg);
         responseOutputStream.flush();
         responseOutputStream.close();
 }

 public void init(ServletConfig servletConfig) throws ServletException {
  super.init(servletConfig);
 }

}




若导入这两个类时报错
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
原因:Eclipse默认把这些受訪问限制的API设成了ERROR。

仅仅要把Windows-Preferences-Java-Complicer-Errors/Warnings里面的Deprecated  and restricted API中的Forbidden references(access rules)选为Warning就能够编译通过。

4.创建用来做验证的servlet
package com.xhc.jcaptcha;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpRetryException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaServiceException;

public class ValidationServlet extends HttpServlet {

 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }
 public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
   throws ServletException, IOException {
  Boolean isResponseCorrect =Boolean.FALSE;
        //remenber that we need an id to validate!
        String captchaId = httpServletRequest.getSession().getId();
        //retrieve the response
        String response = httpServletRequest.getParameter("j_captcha_response");
        // Call the Service method
        httpServletResponse.setContentType("text/html;charset=utf-8");
       PrintWriter wt=httpServletResponse.getWriter();
       
        try {
             isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
                     response);
             if(isResponseCorrect){
              wt.write("<a>验证码输入成功</a>");
             }else{
              wt.write("<a>验证码输入失败</a>");
             }
         } catch (CaptchaServiceException e) {
              //should not happen, may be thrown if the id is not valid
         }
 }

 
 public void init() throws ServletException {
 }

}



5.配置web.xml
 
<servlet>
    <servlet-name>ImageCaptchaServlet</servlet-name>
    <servlet-class>com.xhc.jcaptcha.ImageCaptchaServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>ValidationServlet</servlet-name>
    <servlet-class>com.xhc.jcaptcha.ValidationServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ImageCaptchaServlet</servlet-name>
    <url-pattern>/servlet/ImageCaptchaServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ValidationServlet</servlet-name>
    <url-pattern>/servlet/ValidationServlet</url-pattern>
  </servlet-mapping>


6.jsp页面
<body>
 <form action="servlet/ValidationServlet" method="GET">
  <input type="text" name="j_captcha_response">
  <img src="servlet/ImageCaptchaServlet" height="50" width="100"> 
  <input type="submit" value="提交" />
 </form>
</body>










以上是关于使用jcaptcha插件生成验证码的主要内容,如果未能解决你的问题,请参考以下文章

jcaptcha进阶

Spring中使用Jcaptcha实现校验码验证

验证码-Jcaptcha的使用

java后台验证码工具

jcaptcha配置验证码

本人初学Java,有啥好的图形验证码推荐吗?