Analysis of Java code Generation library Jcaptcha_java

Source: Internet
Author: User

Jcaptcha is very powerful, not only can generate a picture-type verification code, but also can generate sound (Sina uses a dual-authentication code). This article briefly introduces the Jcaptcha library and the use of examples, the following to see.

Download Jcaptcha Library

Maven dependencies are so added:

<dependency>
      <groupId>com.octo.captcha</groupId>
      <artifactid>jcaptcha</ artifactid>
      <version>1.0</version>
    </dependency>

Encapsulates a simple class

Import Com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;
Import Com.octo.captcha.component.image.backgroundgenerator.FileReaderRandomBackgroundGenerator;
Import Com.octo.captcha.component.image.color.RandomListColorGenerator;
Import Com.octo.captcha.component.image.fontgenerator.FontGenerator;
Import Com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;
Import Com.octo.captcha.component.image.textpaster.DecoratedRandomTextPaster;
Import Com.octo.captcha.component.image.textpaster.TextPaster;
Import Com.octo.captcha.component.image.textpaster.textdecorator.TextDecorator;
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.CaptchaEngine; Import Com.octo.captcha.engine.image.ListImageCaptchaEnginE

Import Com.octo.captcha.image.gimpy.GimpyFactory;

Import java.awt.*; /** * Generate the verification code picture class */public class Capchahelper {private static final Integer min_word_length = 4;//Authentication Code Minimum Length private s Tatic Final Integer max_word_length = 4;//verification Code maximum length private static final Integer image_height = 30;//captcha picture height private S Tatic Final Integer image_width = 130;//authentication code picture width private static final Integer min_font_size = 15;//authentication code min font Private St atic final Integer max_font_size = 15;//authentication code max font private static final String Random_word = "0123456789";//random character//validation  Code random font private static final font[] Random_font = new font[]{new Font ("Nyala", Font.Bold, Min_font_size), new Font ("Arial", Font.Bold, min_font_size), New Font ("Bell MT", Font.Bold, min_font_size), new Font ("Credit Vall

  EY ", Font.Bold, Min_font_size), New Font (" Impact ", Font.Bold, Min_font_size)};
 Verification code random color private static final color[] Random_color = new color[]{new Color (255, 255, 255),     New color (255, 255, 255), New color (255, 255, 2.), and A. ()

  , New Color (220, 255, 220)};

  private static Listimagecaptchaengine Captchaengine; public static Captchaengine Getcaptchaengine (final String Imgpath) {if (captchaengine = = null) {synchronized ( Capchahelper.class) {if (Captchaengine = = null && imgpath!= null) {captchaengine = new Listim Agecaptchaengine () {@Override protected void buildinitialfactories () {Randomlistco
              Lorgenerator randomlistcolorgenerator = new Randomlistcolorgenerator (Random_color); Backgroundgenerator backgroundgenerator = new Filereaderrandombackgroundgenerator (image_width, IMAGE_HEIGHT, ImgPath
              );
              Wordgenerator wordgenerator = new Randomwordgenerator (Random_word);
 Fontgenerator fontgenerator = new Randomfontgenerator (min_font_size, Max_font_size, Random_font);             textdecorator[] Textdecorator = new textdecorator[]{}; Textpaster textpaster = new Decoratedrandomtextpaster (min_word_length, Max_word_length, RandomListColorGenerator,
              Textdecorator);
              Wordtoimage wordtoimage = new Composedwordtoimage (Fontgenerator, Backgroundgenerator, Textpaster);
            Addfactory (New Gimpyfactory (Wordgenerator, wordtoimage));
        }
          };
  }} return captchaengine; }
}

Responding to a request for a code image in a Web page

You can define a servlet response to this request, and if so, you springMVC can respond to the request with a certain Controller method in any case, you need to specify a path to servlet或controller the method, such as the path:”/aaa/captcha”

Then in the servlet response to the request to this path , you can write this:

Gets the path to the background image of the captcha, which places many images as background
    String captcha_backgrounds = Session.getservletcontext (). Getrealpath ("/web-inf/ Img/captcha ");
    Captchaengine CE = capchahelper.getcaptchaengine (captcha_backgrounds);
    Need the Admin Web page with JS timing from the server to obtain the current authentication code
    Captcha Captcha = Ce.getnextcaptcha ();
    For verification, the Captcha object is placed in session to validate Req.getsession () when the client submits the authentication code
    (). setattribute ("Captcha", captcha);
    Gets the captcha image, which is an uncompressed bitmap
    bufferedimage image = (bufferedimage) captcha.getchallenge ();
    Resp.setcontenttype ("Image/jpeg");
    Imageio.write (image, "JPG", Resp.getoutputstream ());

If you use Springmvc, write it like this:

Gets the path to the background image of the captcha, which places many images as background
    String captcha_backgrounds = Session.getservletcontext (). Getrealpath ("/web-inf/ Img/captcha ");
    Captchaengine CE = capchahelper.getcaptchaengine (captcha_backgrounds);
    Need the Admin Web page with JS timing from the server to obtain the current authentication code
    Captcha Captcha = Ce.getnextcaptcha ();
    In order to verify, the Captcha object is put into session to validate
    Session.setattribute ("Captcha", CAPTCHA) when the client submits the verification code;
    Gets the captcha image, which is an uncompressed bitmap
    bufferedimage image = (bufferedimage) captcha.getchallenge ();
    Bytearrayoutputstream bao=new Bytearrayoutputstream ();
    should be reduced to JPG and written to the output stream
    imageio.write (image, "jpg", Bao);
    return Bao.tobytearray ();

In both of these ways, the data returned to the client is binary.

String captcha_backgrounds = session.getServletContext().getRealPath(“/WEB-INF/img/captcha”);

To indicate that the path /WEB-INF/img/captcha is placed below the background of the verification code image of multiple pictures, must be jpeg, size may not be limited, you can try it yourself.

Use point to this address in Web pages

 
 

JS function in refreshCaptchaImg() response to the click of the picture, each click, and then retrieve a new verification code picture. How do I get a picture of the code again?

Just change the src attribute of the IMG, but here you set this property with the same address each time, so that it does not cause a real refresh, so refreshCaptchaImg() the method is implemented as follows:

function refreshcaptchaimg () {
      //download the verification code picture from the server
      //To this parameter pure in order to force the refresh, otherwise, because src points to the URL address has not changed, the browser will not really refresh the picture
      var now = new Date ()
      $ ("#captcha"). attr ("src", "/captcha_img?") +now.gettime ());

The above is the Java Code Generation Library Jcaptcha Introduction and use, I hope to learn Java Help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.