Code accumulation-Generate CAPTCHA servlet

Source: Internet
Author: User

 Packageweb;ImportJava.awt.Color;ImportJava.awt.Font;ImportJava.awt.Graphics2D;ImportJava.awt.image.BufferedImage;Importjava.io.IOException;ImportJava.util.Random;ImportJavax.imageio.ImageIO;Importjavax.servlet.ServletException;ImportJavax.servlet.ServletOutputStream;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession; Public classCheckcodeextendsHttpServlet {Private Static Final LongSerialversionuid = -5051097528828603895l; /*** The name of the verification code session. */    Private Static FinalString session_att_name = "Validatecode"; /*** Verify the width of the code picture. */    Private intwidth = 100; /*** Verify the height of the code picture. */    Private intHeight = 30; /*** Number of verification code characters*/    Private intCodecount = 4; /*** Font height*/    Private intFontheight; /*** The x-axis value of the first character, because the subsequent character coordinates increment sequentially, so their x-axis value is a multiple of Codex*/    Private intCodeX; /*** Codey, verify the y-axis value of the character, because parallel so the value is the same*/    Private intCodey; /*** Codesequence Indicates the sequence value that the character is allowed to appear*/    Char[] codesequence = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ',            ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ',            ' X ', ' Y ', ' Z ', ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ' }; /*** Initialize Verify picture properties*/     Public voidInit ()throwsservletexception {//getting initial information from Web. XML//widthString Strwidth = This. Getinitparameter ("width"); //HeightString strheight = This. Getinitparameter ("height"); //Number of charactersString Strcodecount = This. Getinitparameter ("Codecount"); //convert the configured information to a numeric value        Try {            if(Strwidth! =NULL&& strwidth.length ()! = 0) {width=Integer.parseint (strwidth); }            if(Strheight! =NULL&& strheight.length ()! = 0) {Height=Integer.parseint (strheight); }            if(Strcodecount! =NULL&& strcodecount.length ()! = 0) {Codecount=Integer.parseint (Strcodecount); }        } Catch(NumberFormatException e) {e.printstacktrace (); }        //width-4 Remove the left and right positions, so that the verification code more concentrated display, reduce the more concentrated. //codecount+1//equal to the width of the display, including the left and right sides of the spaceCodeX = (width-4)/(codecount+1); //height-10 Centralized display verification codeFontheight = height-10; Codey= Height-7; }     Public voidService (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//defining the image bufferBufferedImage buffimg =Newbufferedimage (width, height, bufferedimage.type_int_rgb); Graphics2D GD=Buffimg.creategraphics (); //Create a random number generator classRandom random =NewRandom (); //fill the image with whiteGd.setcolor (Color.light_gray); Gd.fillrect (0, 0, width, height); //To create a font, the size of the font should depend on the height of the image. Font font =NewFont ("Fixedsys", Font.plain, fontheight); //sets the font. Gd.setfont (font); //draw a border. Gd.setcolor (Color.Black); Gd.drawrect (0, 0, width-1, height-1); //randomly generates 160 lines of interference so that the authentication code in the image is not easily detected by other programs. Gd.setcolor (Color.gray);  for(inti = 0; I < 16; i++) {            intx =random.nextint (width); inty =random.nextint (height); intXL = Random.nextint (12); intYL = Random.nextint (12); Gd.drawline (x, y, x+ XL, Y +yl); }        //The Randomcode is used to save randomly generated verification codes so that users can log in and authenticate. StringBuffer Randomcode =NewStringBuffer (); intRed = 0, green = 0, blue = 0; //random generation of Codecount number verification code.          for(inti = 0; i < Codecount; i++) {            //get a randomly generated captcha number. String Strrand = string.valueof (Codesequence[random.nextint (36)]); //generates a random color component to construct a color value so that the output will have a different color value for each digit. Red = Random.nextint (255); Green= Random.nextint (255); Blue= Random.nextint (255); //draws the verification code into the image with a randomly generated color. Gd.setcolor (NewColor (Red,green,blue)); Gd.drawstring (Strrand, (i+ 1) *CodeX, Codey); //The resulting four random numbers are grouped together. randomcode.append (Strrand); }        //Save the four-digit verification code to the session. HttpSession session =request.getsession ();        Session.setattribute (Session_att_name, randomcode.tostring ()); //suppresses image caching. Response.setheader ("Pragma", "No-cache"); Response.setheader ("Cache-control", "No-cache"); Response.setdateheader ("Expires", 0); Response.setcontenttype ("Image/jpeg"); //output the image to the servlet output stream. Servletoutputstream SOS =Response.getoutputstream (); Imageio.write (buffimg,"JPEG", SOS);    Sos.close (); }          Public StaticString Getvalidatecode (httpservletrequest request) {HttpSession session=request.getsession (); Object obj=Session.getattribute (session_att_name); if(obj!=NULL){                returnobj.tostring (); }            return""; }         Public Static voidRemovevalidatecode (HttpServletRequest request) {HttpSession session=request.getsession ();        Session.removeattribute (Session_att_name); }}

Code accumulation-Generate CAPTCHA servlet

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.