Currently, many websites require verification codes when users fill out forms. One purpose of the Verification Code is to prevent malicious websites from downloading software, these software can download all webpages of the website by traversing links. It also prevents users from using website resources without passing through the pages of the website. Therefore, many websites now use the verification code technology. The verification code is usually a random string generated on the WEB server and saved in a certain way, for example, to the current Session, then, when a user submits a webpage, the verification result is consistent with that entered by the user. However, if the webpage is directly in plain text, some software with strong functions cannot be prevented from automatically entering the form. Therefore, the verification code is usually displayed in the form of an image, and the strings displayed in the image can be processed, such as rotating characters, add background textures and other technologies to make it more difficult to be recognized by software. The following describes how to implement the verification code:
First, implement a servlet to generate images (of course, jsp can also be used ):
Import javax. servlet .*;
Import javax. servlet. http .*;
Import java. io .*;
Import java. util .*;
Import com.sun.image.codec.jpeg .*;
Import java. awt .*;
Import com.sun.image.codec.jpeg .*;
Import java. awt. image. BufferedImage;
Import java. awt. image. DataBuffer;
Import java. awt. geom. GeneralPath;
Import javax. swing .*;
Import java. math .*;
Public class Servlet1
Extends HttpServlet {
// Process the HTTP Get request
Public void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
Response. setContentType (CONTENT_TYPE );
Response. setContentType ("image/jpeg"); // you must set ContentType to image/jpeg.
Int length = 4; // The default value is 4.
Date d = new Date ();
Long lseed = d. getTime ();
Java. util. Random r = new Random (lseed); // set Random Seed