验证码

1.

Add jcaptcha-all.jar (provided in bin-distribution) and commons-collection-3.2 or greater (not provided see commons collection ) to your application class path, ie in you WEB-INF/lib folder.

 

2.

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

 

public class CaptchaServiceSingleton {
    private static ImageCaptchaService instance ;
    static {
     instance = new DefaultManageableImageCaptchaService(
      new FastHashMapCaptchaStore(),
      new MyImageCaptchaEngine(),
      180,
      100000,
      75000);
    }
    public static ImageCaptchaService getInstance(){
        return instance;
    }
}

import java.awt.Color;
import java.awt.Font;

import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.FunkyBackgroundGenerator;
import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;
import com.octo.captcha.component.image.color.RandomRangeColorGenerator;
import com.octo.captcha.component.image.fontgenerator.FontGenerator;
import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
import com.octo.captcha.component.image.textpaster.RandomTextPaster;
import com.octo.captcha.component.image.textpaster.TextPaster;
import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;
import com.octo.captcha.component.image.wordtoimage.WordToImage;
import com.octo.captcha.component.word.wordgenerator.RandomWordGenerator;
import com.octo.captcha.component.word.wordgenerator.WordGenerator;
import com.octo.captcha.engine.image.ListImageCaptchaEngine;
import com.octo.captcha.image.gimpy.GimpyFactory;

public class MyImageCaptchaEngine extends ListImageCaptchaEngine {
    protected void buildInitialFactories() {
           WordGenerator wgen = new RandomWordGenerator("ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789");
           RandomRangeColorGenerator cgen = new RandomRangeColorGenerator(
                new int[] {0, 100},
                new int[] {0, 100},
                new int[] {0, 100});

           //生成验证码的个数
           TextPaster textPaster = new RandomTextPaster(new Integer(4), new Integer(4), cgen, true);

            //验证码的图片的大小

           BackgroundGenerator backgroundGenerator = new FunkyBackgroundGenerator(new Integer(200), new Integer(100));
           BackgroundGenerator back = new UniColorBackgroundGenerator(
                   new Integer(100), new Integer(50), Color.white);
          //字体大小
           Font[] fontsList = new Font[] {
               new Font("Arial", 0, 5),
               new Font("Tahoma", 0, 5),
               new Font("Verdana", 0, 5),
            };

            FontGenerator fontGenerator = new RandomFontGenerator(new Integer(20), new Integer(35), fontsList);

            WordToImage wordToImage = new ComposedWordToImage(fontGenerator, back, textPaster);
            this.addFactory(new GimpyFactory(wgen, wordToImage));
    }
}

3. Code an image captcha servlet

 

    

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();
    }
}
4.Add it to your web.xml
 

        jcaptcha
        ImageCaptchaServlet
        0
    

And


        jcaptcha
        /jcaptcha
    
5

The form

Provide a form containing the captcha challenge (the image) and an input text for the response

"/jcaptcha">
6 the validation routine
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
            try {
                isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
                        response);
            } catch (CaptchaServiceException e) {
                 //should not happen, may be thrown if the id is not valid
            }

//do something according to the result!

你可能感兴趣的:(验证码)