JSP Production Verification Code

Source: Internet
Author: User
Tags canvas rectangle set background

Verification Code

The Verification Code (CAPTCHA) is the abbreviation for "Completely Automated public Turing test to tell Computers and humans Apart" (fully automated computer-and human-Turing test), is a public automatic program that distinguishes whether a user is a computer or a person. Can prevent: Malicious hack password, brush tickets, forum irrigation, effectively prevent a hacker to a particular registered users with a specific program brute force to make a continuous attempt to break the way, in fact, with the verification code is now a lot of web site way, we use a relatively simple way to achieve this function. This problem can be generated and judged by a computer, but only humans can answer it. Since the computer is unable to answer the CAPTCHA question, the user who answers the question can be considered human.

JSP production Verification Code operating environment: TOMCAT+ECLIPSE+JDK Basic idea: Now the servlet to draw a verification code of the picture, so that it appears on the page, and then use the JS method can refresh the verification code, You can use Ajax to get the value entered by the user through the servlet with the verification code to determine whether, and the basic method of prompting the user:
        • BufferedImage:

            • The image is an abstract column, and BufferedImage is an implementation of the image.
              The main function of image and BufferedImage is to load a picture into memory.
              The way in which Java loads a picture into memory is:
              Java code
              String Imgpath = "D:/demo.jpg";
              BufferedImage image = Imageio.read (new FileInputStream (Imgpath));
              This method can get the details of the picture, for example: Get the width of the picture: Image.getwidth (null); Images can be processed further by loading in memory only.
        • Graphics:
          • The Graphics class provides basic geometric drawing methods, such as drawing line segments, drawing rectangles, drawing circles, drawing colored shapes, drawing ellipses, drawing arcs, drawing polygons, and so on, and I recommend that you take a look at the methods of drawing using the Java Graphics class.
Code implementation of verification code

I do the verification code is displayed in Chinese, you can change in the servlet to show whether you want to display a number or a letter or a combination, you can use the array to store these, you can also convert ASCII code by random numbers, to see a person's preferences

The first place to make a code in a JSP

<Divclass= "Row cl">        <Div>          <inputtype= "text"placeholder= "Verification Code"value= "Verification Code:"onblur= "Testcheck (this.value);">          <imgID= "Pic"src= "Checktestservlet"> <aID= "Kanbuq"OnClick= "checktest ();">I can't see clearly.</a> </Div> </Div>

In a servlet called Checktestservlet.java.

@WebServlet ("/checktestservlet") Public classChecktestservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//This method implements the verification code generationResponse.setcharacterencoding ("Utf-8"); //Create a picture buffer set its size bufferedimage (int width, int height, int imageType)BufferedImage bimage=NewBufferedImage (100, 30, BUFFEREDIMAGE.TYPE_3BYTE_BGR); //Create a canvas on a bufferGraphics g=Bimage.getgraphics (); //Set Background colorG.setcolor (Color.orange); //Create a canvas rectangle, position (0,0) point, size 100,30G.fillrect (0, 0, 100, 30); //creating random ObjectsRandom r=NewRandom (); intIndex//Store Random Numbers//get the text things stored in placeStringBuffer sbuffer=NewStringBuffer (); //Loop produces four words                   for(inti = 0; I < 4; i++) {                      //The first hexadecimal code in Chinese text is 4e00 to decimal is 19968, the last one is 9fa0 decimal is 40869, so you can generate a random number between thisIndex=r.nextint (40869-19968+1) +19968;//Generate random numbers//set the random color,G.setcolor (NewColor (R.nextint (255), R.nextint (255), R.nextint (255))); //set the type of text, sizeG.setfont (NewFont ("", Font.Bold, 20)); /*stooped, converts a random number to hexadecimal integer.tohexstring (index), 16) and then converts the character (char) (Integer.parseint, where each text is set */g.drawstring ((Char) (Integer.parseint (integer.tohexstring (index), +)) + "", I*22+4, 18); //Store it in stringbuffer so that it can be read later for comparisonSbuffer.append ((Char) (Integer.parseint (integer.tohexstring (index), 16))); }                  //set the resulting text to the sessionRequest.getsession (). SetAttribute ("Piccode", sbuffer.tostring ()); /*Read and write this captcha image to the page * Write (RenderedImage im, String formatname, outputstream output) */Imageio.write (Bimage,"JPG", Response.getoutputstream ()); }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stubdoget (request, response); }

In doing a JS refresh verification code, for unclear, or other refreshing use

    function CheckTest () {         var time=new Date (). GetTime ();        $ ("#pic"). attr (' src ', ' checktestservlet?d= ' +time)    }

Then write an Ajax to verify that the user entered the correct return prompt, this is done with jquery, need to draw JS

function Testcheck (num) {        $.ajax ({            type: "POST",//Submit by            URL: "Testcheckservlet",//Submit address            async:true,/ /whether the asynchronous request            DataType: "HTML",//return type            data:{"num": num},//pass past the value            success:function (data,textstatus) {// Successfully executed method                $ ("#checks"). HTML (data)            },            error:function () {//Failed to execute method                alert ("Error");}        )    

It's a bit of a hassle to do a servlet to verify that the value the Ajax is passing matches the verification code.

@WebServlet ("/testcheckservlet") Public classTestcheckservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.setcharacterencoding ("Utf-8"); PrintWriter out=Response.getwriter (); //The verification code obtained by the input is compared with the random picture Verification code, and the judgment is equal, and the user is prompted.        if(Request.getsession (). getattribute ("Piccode"). ToString (). Equals (Request.getparameter ("num")) {out.println ("Verification code is correct"); }Else{out.println ("Captcha Error"); }    }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stubdoget (request, response); }}

In this way the verification code has been basically done, there are many needs to modify the content, patterns, according to the needs of

"Version Declaration" Reproduced please note the source

JSP Production Verification Code

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.