1. 首页
  2. 博客
  3. 详情

jcaptcha图形验证码组件使用

LovePanda  • 

jcaptcha是一个开源的用来生成图形验证码的Java开源组件,使用起来也是非常的简单方便。

jcaptcha官网:http://jcaptcha.sourceforge.net/

使用:

1.在pom.xml中加入:

      <!-- jcaptcha -->
      <dependency>
          <groupId>commons-collections</groupId>
          <artifactId>commons-collections</artifactId>
          <version>3.0</version>
      </dependency>
      <dependency>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
          <version>1.1.3</version>
      </dependency>
      <dependency>
          <groupId>com.octo.captcha</groupId>
          <artifactId>jcaptcha</artifactId>
          <version>1.0</version>
      </dependency>


2.代码:


CaptchaServiceSingleton.java

package com.fly.servlet;
/**
 * Created by lovepanda 2016/8/5.
 */
import com.octo.captcha.component.image.backgroundgenerator.GradientBackgroundGenerator;
import com.octo.captcha.component.image.color.SingleColorGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.NonLinearTextPaster;
import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;
import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;
import com.octo.captcha.engine.GenericCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;
import com.octo.captcha.service.captchastore.FastHashMapCaptchaStore;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import java.awt.*;
public class CaptchaServiceSingleton {
    private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService(
            new FastHashMapCaptchaStore(),
            new GenericCaptchaEngine(
                    new GimpyFactory[]{new GimpyFactory(
                            new RandomWordGenerator("abcdefkmnpqrsuvwxy345678"),
                            new ComposedWordToImage(
                                    new RandomFontGenerator(20, 20,new Font[]{new Font("Arial", 20, 20)}),
                                    new GradientBackgroundGenerator(90, 30, new SingleColorGenerator(new Color(235, 255, 255)), new SingleColorGenerator(new Color(255, 195, 230))),
                                    new NonLinearTextPaster(4, 4, new Color(11, 11, 11))
                            )
                    )}
            ),
            180,
            180000,
            20000
    );
    public static ImageCaptchaService getInstance() {
        return instance;
    }
}


ImageCaptchaServlet.java

package com.fly.servlet;
/**
 * Created by lovepanda 2016/8/5.
 */
import com.octo.captcha.service.CaptchaServiceException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
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 java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ImageCaptchaServlet extends HttpServlet {
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
    }
    protected 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 =
                    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();
    }
}

在web.xml中加入

    <servlet>
        <servlet-name>jcaptcha</servlet-name>
        <servlet-class>com.kland.servlet.ImageCaptchaServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>jcaptcha</servlet-name>
        <url-pattern>/jcaptcha</url-pattern>
    </servlet-mapping>

到这一步访问:   项目名/jcaptcha就可以得到验证码了,效果:


那么怎么验证呢?Jcaptcha有自己的验证方法,如下

Boolean isResponseCorrect =Boolean.FALSE;
        String captchaId = request.getSession().getId();
        try {
            isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
                    verify);
            //isResponseCorrect 即是验证结果
        } catch (CaptchaServiceException e) {
           
        }

完成收工。如果要调整验证码样式的话直接修改CaptchaServiceSingleton.java的代码即可,如颜色,指定允许那些字符,字体,图片大小等。


声明:若要转载LovePanda中的任何博客请注明转载地址

分享到
LovePanda登录 ×
LovePanda注册 ×