Discussion on Java Verification Code production (last article) _java

Source: Internet
Author: User
Tags browser cache java web stringbuffer

I believe that the verification code this thing will not be unfamiliar, whether it is to apply for account or in some cases, you will be required to enter the verification code. After statistics, verification code validation on the successful adoption of the probability is 90%, is not high, so many people for this reduction of user experience degree of design will certainly doubt his necessity, but Hegel said: All rational things are realistic; everything that is realistic is rational. Next we'll look at the captcha.

Verification code is a difference between the user is a computer or a person's public fully automated program, he was used to prevent malicious crack passwords, brush tickets, forum irrigation, to prevent hackers through brute force to constantly log on, applied to banks, communities, forums, voting systems and so on.

No more nonsense. Let's take a look at the four ways that I've known to implement CAPTCHA in Java.

Method One:

The first method is my first thought, but also the simplest implementation of logic, but efficiency, security is extremely low.

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

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

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

4. Get the string in the component or text box to compare the string in each picture with the Equals () method at the time of submission

The flaw is to make the verification code picture process is too time-consuming, the implementation method extremely low, extremely does not recommend this realization, the following method will be more efficient and beautiful relatively safe.

Method Two:

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

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

When we click "See not clear", the verification code picture will be a refresh, will call a JS function to reset the picture path to replace the picture, please see the following code, Code <%=request.getcontextpath ()%> is to solve the problem of relative path, Can return to the root path of the site, and/servlet/imageservlet is a whole, pointing to the Imageservlet servlet, why to add a/servlet before, Because we did a configuration mapping in Web.xml, we can understand that a longer name is changed. Then look at the following JS function, some people may have questions, why get a current time and then add to the path at the end of it, in fact, this is to solve the browser cache problem, is when the imageservlet after the trigger, although the verification code picture changed but the cache has not changed the display of the Verification code picture unchanged problem, The browser cache can be invalidated by the time difference between times.

<script type= "Text/javascript" >
  function Reloadcode () {
   var time = new Date (). GetTime ();
   document.getElementById ("Imagecode"). src= "<%=request.getcontextpath ()%>/servlet/imageservlet?d=" +time;
  }
 </script>

The following are key configuration information in Web.xml:

<script type= "Text/javascript" >
 function Reloadcode () {
  var time = new Date (). GetTime ();
  document.getElementById ("Imagecode"). src= "<%=request.getcontextpath ()%>/servlet/imageservlet?d=" +time;
 }
 </script>

And then we'll see how the key Imageservlet is creating the picture:

<servlet>
  <servlet-name>ImageServlet</servlet-name>
  <servlet-class> com.muke.imageservlet</servlet-class>
 </servlet>
 <servlet>
  <servlet-name> loginservlet</servlet-name>
  <servlet-class>com.muke.LoginServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>ImageServlet</servlet-name>
  <url-pattern>/servlet/ImageServlet</url-pattern>
 </servlet-mapping>
 < servlet-mapping>
  <servlet-name>LoginServlet</servlet-name>
  <url-pattern>/ Servlet/loginservlet</url-pattern>
 

If you want to more vivid description of how the verification code to achieve, then a word "painting", sounds like the first method, or relatively low, but the code to automatically "draw" the verification code efficiency absolutely turned the number of times. Let's take a look at the above code, first instantiate a BufferedImage object Bi,bi is used to draw the verification code picture, and then use BI to get a brush g, with G to draw the solid rectangle background, and then use the simple logic of brush G to invoke 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 finally save the comparison 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 kind of picture format to the ImageIO stream.

The following loginservlet can be seen, get just imageservlet into the session string can be compared with the Verification Code submission box string, you can turn the string into lowercase or uppercase do a ignore case processing.

 public class Imageservlet extends HttpServlet {public
 void doget (HttpServletRequest request, HttpServletResponse Response) throws ioexception{
  bufferedimage bi = new BufferedImage (,, Bufferedimage.type_int_rgb);
  Graphics g = Bi.getgraphics ();
  Color c = new color (,,);
  G.setcolor (c);
  G.fillrect (,,,);
  char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ". ToCharArray ();
  Random r = new Random ();
  int len=ch.length,index;
  StringBuffer sb = new StringBuffer ();
  for (int i=; i<; i++) {
  index = r.nextint (len);
  G.setcolor (New Color (R.nextint (), R.nextint (), R.nextint ()));
  g.DrawString (ch[index]+ "", (i*) +,);
  Sb.append (Ch[index]);
  Request.getsession (). setattribute ("Piccode", sb.tostring ());
  Imageio.write (BI, "JPG", Response.getoutputstream ());
 }
 

The following is the implementation legend:

The above is a small set to introduce the Java Verification Code production related knowledge, hope to help everyone! Follow up to introduce Java verification Code production (next), interested friends please pay attention to cloud Habitat community website!

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.