Java Web (four) code implementation of one-time verification code

Source: Internet
Author: User

In fact, the logic of implementing the code is very simple, really super super simple.

1, on the login page login.jsp will verify the code picture using the label will draw the URL of the captcha image to it

2, on the server side of two servlet, one is used to draw the verification code picture of the Verifycodeservlet, and the other is to verify that the verification code at login is correct or not repeated Loginservlet

3, in the Verifycodeservlet, the verification Code of four letters into the session, and then in the Loginservlet, the request submitted in the verification code and the session in the comparison, if correct, then verify the success, and the verification code in the session is deleted, why delete? Ensure that the data in the session can only be used once, prevent repeated data submission, if not correct, use request, save the error message, and then request forward to the login page to display the error message, if the data in the session is found to be null, indicating that the data is repeatedly submitted, The error message is also returned to the login page in the same way.

The difficulty lies in: Verifycodeservlet code implementation. The code for the drawing is not very familiar.


login.jsp

  <body>            <%        = (String) request.getattribute ("MSG");         if NULL ) {            out.print (msg);        }     %>        <form action= "/test01/loginservlet" method= "POST" >         User name:<input type= "text" name = "username"/> <br/>         captcha:<input type= "text" name= "Verifycode" size= "5"/>  <br/>        <input type=" Submit "value=" submitted "/>    </form>   </body>
View Code

Verifycodeservlet.java

     Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//Declaration Verification Code        intwidth = 60; intHeight = 30; String Data= "ABCDEFGHJKLMNPQRSTUVWXYZ23456789ABCDEFGHIJKLMNPQRSTUVWXYZ";//random character dictionary, where 0,o,1,i and other hard-to-discern characters are best notRandom random =NewRandom ();//Random Class//1 Creating a picture data cache area (core Class)BufferedImage image =NewBufferedImage (width, height, bufferedimage.type_int_rgb);//Create a picture of a color//2 Get Artboards (Pictures, PS layers), paint objects. Graphics g =Image.getgraphics (); //3 Choose Color, Draw rectangle 3, 4 step is to draw an effect with inside and outside borderG.setcolor (Color.Black); G.fillrect (0, 0, width, height); //4 White RectangleG.setcolor (Color.White); G.fillrect (1, 1, width-2, height-2); /**1 Cache area is provided, in order to store 4 random characters, in order to deposit the session*/StringBuilder Builder=NewStringBuilder (); //5 randomly generated 4 characters//Set Font ColorG.setfont (NewFont ("Arial", Font.bold&font.italic, 20));  for(inti = 0; I < 4; i + +){            //Random ColorG.setcolor (NewColor (Random.nextint (255), Random.nextint (255), Random.nextint (255))); //Random characters            intindex =Random.nextint (Data.length ()); String Str= data.substring (index, index + 1); /**2 Cache*/builder.append (str); //Writeg.DrawString (str, (WIDTH/6) * (i + 1), 20); }        //Draw the noise point in the diagram so that the picture is not so well identified         for(intJ=0,n=random.nextint (j<n;j++);) {g.setcolor (color.red); G.fillrect (Random.nextint (width), random.nextint (height),);//Random Noise Point        }                /**3 get random data and save session*/String TempStr=builder.tostring (); Request.getsession (). SetAttribute ("Sessioncachedata", TEMPSTR); //: Generate picture to send to browser--equivalent to downloadImageio.write (image, "JPG", Response.getoutputstream ()); }
View Code

Loginservlet.java

     Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//1 Get user-entered verification codeString Verifycode = Request.getparameter ("Verifycode"); //2 Get the server session store data if NULL is not returnedString sessioncachedata = (string) request.getsession (). getattribute ("Sessioncachedata"); //* Remove the server cache session dataRequest.getsession (). RemoveAttribute ("Sessioncachedata"); //* * Determine if the server exists        if(Sessioncachedata = =NULL) {Request.setattribute ("MSG", "Please do not repeat commit"); Request.getrequestdispatcher ("/login.jsp"). Forward (request, response); return; }        //3 Comparison        if(!sessioncachedata.equalsignorecase (Verifycode)) {            //User Input Error//* Store Request ScopeRequest.setattribute ("msg", "Captcha input Error"); //* Request ForwardingRequest.getrequestdispatcher ("/login.jsp"). Forward (request, response); return; }                //...... Login Action    }     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException { This. Doget (request, response); }}
View Code

:

    

When the captcha is wrong:

      

Attention:

If you want to copy the code, you need to change the URL, you must be different from me, and some people set the servlet access path is not the same, so copy only need to copy the key code.

  

Java Web (four) code implementation of one-time 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.