Java Verification Code Authoring (top)

Source: Internet
Author: User
Tags browser cache

I believe that you can not be unfamiliar with the code, whether it is the application account or in some cases when the login will be required to enter a verification code. After statistics, verification code once the probability of success Pass is 90%, not high, so many people for this reduction of user experience of the design will certainly doubt his necessity, but Hegel said: All rational things are realistic, all the real things are reasonable. Next, let's look at the verification code.

Verification code is a user is a computer or a human public automatic program, he was used to prevent malicious password, brush tickets, forum irrigation, to prevent hackers through brute force to constantly log in, applied to banks, communities, forums, voting systems and so on.

Don't talk about it. Let's take a look at the four ways I know to implement CAPTCHA in Java.

Method One:

The first approach I thought of first, but also to achieve the simplest logic, but the efficiency, security is extremely low.

The specific operation is: 1, using Photoshop to make a verification code picture, the rectangle picture can have the necessary English letters, numbers or Chinese (as above)

2. Display the picture in the swing control or in a JSP page

3, in the code for each picture matching the corresponding Captcha string

4. Gets the string in the component or text box at the time of submission compared with the string for each picture with the Equals () method

Defect is the process of making verification code picture is too time-consuming, the implementation method is very low, it is not recommended to implement, the following method will be more efficient and beautiful relatively safe.

Method Two:

This is the implementation of Java Web,servlet Verification Code, the implementation of logic is still very clear.

To save the simpler implementation code, let's start with the key code in the foreground:

When we click "Can't see", the CAPTCHA image will be a refresh, will call a JS function to re-set the picture path to replace the picture, see the code below, <%=request.getcontextpath ()%> is to solve the relative path problem, can return the root path of the site, and/servlet/imageservlet is a whole, pointing to imageservlet this servlet, why to add a/servlet before, Because we did a configuration mapping in Web. XML, we can understand that we've changed a longer name. Then look at the following JS function, some people may have doubts, why get a current time and then add in the path at the end, in fact, this is to solve the problem of browser cache, is when the imageservlet triggered after the verification code picture changed but the cache has not changed the display of the verification Code picture unchanged, The browser cache can be invalidated with different time of day.

1 <script type= "Text/javascript" >2       function Reloadcode () {3             New  Date (). GetTime (); 4            document.getElementById ("Imagecode"). src= "<%=request.getcontextpath ()%>/servlet/imageservlet?d=" +  Time; 5        }6 </script>
js function

Here is the key configuration information in Web. XML:

1<servlet>2<servlet-name>ImageServlet</servlet-name>3<servlet-class>com.muke.imageservlet</servlet-class>4</servlet>5<servlet>6<servlet-name>LoginServlet</servlet-name>7<servlet-class>com.muke.loginservlet</servlet-class>8</servlet>9<servlet-mapping>Ten<servlet-name>ImageServlet</servlet-name> One<url-pattern>/servlet/ImageServlet</url-pattern> A</servlet-mapping> -<servlet-mapping> -<servlet-name>LoginServlet</servlet-name> the<url-pattern>/servlet/LoginServlet</url-pattern> -</servlet-mapping>
Web. XML

Then we see how the key Imageservlet is creating the picture:

1  Public classImageservletextendsHttpServlet {2  Public voidDoget (HttpServletRequest request, httpservletresponse response)throwsioexception{3BufferedImage bi =NewBufferedImage (68,22, Bufferedimage.type_int_rgb);4Graphics g =bi.getgraphics ();5Color C =NewColor (200,150,255);6 G.setcolor (c);7G.fillrect (0, 0, 68, 22);8         Char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789". ToCharArray ();9Random r =NewRandom ();Ten         intlen=Ch.length,index; OneStringBuffer SB =NewStringBuffer (); A          for(inti=0; i<4; i++){ -index =R.nextint (len); -G.setcolor (NewColor (R.nextint), R.nextint (188), R.nextint (255))); theg.DrawString (ch[index]+ "", (i*15) +3, 18); - sb.append (Ch[index]); -         } -Request.getsession (). SetAttribute ("Piccode", sb.tostring ()); +Imageio.write (BI, "JPG", Response.getoutputstream ()); -     } +}
Imageservlet

If you want to more vividly describe how this verification code is implemented, then a word "painting", it sounds like the first method, or relatively low, but the code to automatically "draw" The verification code efficiency is absolutely no more than a few times. Let's take a look at the above code, first instantiate a BufferedImage object Bi,bi is used to draw the captcha image, then use BI to get a brush g, with G to draw the solid rectangle background, and then use simple logic through the brush g to call Java common drawstring () method to draw the verification code character on the rectangle, and then add the string to the StringBuffer variable string object, and then to the JSP built-in object session in order to submit the verification code, in order to display the verification code, We also need to write the generated captcha picture in some image format to the ImageIO stream.

As can be seen in the following loginservlet, get just imageservlet into the session of the string can be compared with the verification code in the box string in the match, you can change the string to lowercase or uppercase to do a case-insensitive processing.

1  Public classLoginservletextendshttpservlet{2      Public voidDoget (HttpServletRequest request, httpservletresponse response)throwsioexception{3String piccode = (string) request.getsession (). getattribute ("Piccode");4String Checkcode = Request.getparameter ("Checkcode");5Checkcode =checkcode.touppercase ();6Response.setcontenttype ("TEXT/HTML;CHARSET=GBK");7PrintWriter out =Response.getwriter ();8         if(Checkcode.equals (Piccode)) {9Out.println ("Verify code entered correctly! ");Ten}Else{ OneOut.println ("Verification code input Error!!! "); A         } - Out.flush (); - out.close (); the     } -}
Loginservlet

Here is the implementation legend:

Not finished, see (next) http://www.cnblogs.com/justcaxzm/p/5494959.html

Java Verification Code Authoring (top)

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.