Random verification code using servlet

xiaoxiao2021-03-06  100

Picture Effect: Import Javax.Servlet. *; Import Javax.Servlet.http. *; Import Java. (IMPORT JAVA.ATIL. *; Import Java.awt. *; Import Java.awt.image. *; Import Java.util. *; Import javax.imageio. *; import com.sun.image.codec.jpeg. *;

Public class validimage extends httpservlet {private static final string content_type = "image / jpeg; charSet = GB2312"

// Initialize Global Variables Public Void Init () THROWS ServleTexception {}

// Process the HTTP Get request public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType (CONTENT_TYPE); // set the page is not cached

HttpSession session = request.getations ();

Response.setHeader ("Pragma", "No-cache"); Response.setHeader ("Cache-Control", "No-cache"); Response.SetDateHeader ("Expires", 0); // Create a diagram in memory like int width = 60, height = 20; BufferedImage image = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB); // Get the graphics context graphics g = image.getGraphics (); // set the background color g.setColor (getRandColor (155, 254)); //g.SetColor (New Color (255, 255, 255)); g.FillRect (0, 0, width, height); // Set font G.SetFont (New Font ("Times New Roman", Font .Plain, 18)); // Sea Box //g.SetColor (New Color ()); //g.drawRect (0, 10 ,width-1, Height 1); // Randomly generate 155 interference lines Make the authentication code in the image is not easy by other programs to detect G.SetColor (GetrandColor (160, 220));

/ / Generate random random random = new random ();

For (int i = 0; i <155; i ) {int x = random.nextint (width); int y = random.nextint (INT XL = random.nextint (12); int yl = random.nextint (12); g.drawline (x, y, x xl, y );} // Take the randomly generated authentication code (4 digits) string srand = ""; for (int i = 0; i < 4; i ) {string rand = string.valueof (random.nextint (10)); SRAND = rand; // Display the authentication code to G.SetColor (New Color (20 random.nextint (110), 20 random.nextint (110), 20 random.nextint (110)))))))))))))))))))))))) // The color of the call function is the same, it may be because the seed is too close, so you can only generate G. DrawString (Rand, 13 * i) 6, 16);} // Deposit the authentication code into session session.setttribute ("randcode", srand); // Image take effect g.dispose (); // Output image to page imageio.write (image, "JPEG", response.getOutputStream ());}

Color GetrandColor (int FC, int BC) {// given random color random random = new random (); if (fc> 255) fc = 255; if (bc> 255) BC = 255; int R = FC Random.Nextint (BC-FC); INT G = fc random.nextint (BC-FC); int b = fc random.nextint (BC-FC); Return New Color (R, G, B);}

// Clean Up Resources Public Void Destroy () {}} This creates a RANDCode session here, and the user verifies this verification code in the second page.

转载请注明原文地址:https://www.9cbs.com/read-95713.html

New Post(0)