Copy codeThe Code is as follows:
<% @ Page language = "java" pageEncoding = "gbk" %>
<% @ Page contentType = "image/jpeg" import = "java. awt .*,
Java. awt. image. *, java. util. *, javax. imageio. * "%>
<%!
Color getRandColor (int fc, int bc) {// obtain a random Color from a given range
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 );
}
%>
<%
// Set the page not to cache
Response. setHeader ("Pragma", "No-cache ");
Response. setHeader ("Cache-Control", "no-cache ");
Response. setDateHeader ("Expires", 0 );
// Create an image in memory
Int width = 60, height = 20;
BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB );
// Obtain the image Context
Graphics g = image. getGraphics ();
// Generate a random class
Random random = new Random ();
// Set the background color
G. setColor (getRandColor (200,250 ));
G. fillRect (0, 0, width, height );
// Set the font
G. setFont (new Font ("Times New Roman", Font. PLAIN, 18 ));
// Draw a border
// G. setColor (new Color ());
// G. drawRect (0, 0, width-1, height-1 );
// Generates 155 random interference lines, making the authentication code in the image hard to be detected by other programs.
G. setColor (getRandColor (160,200 ));
For (int I = 0; I <155; I ++)
{
Int x = random. nextInt (width );
Int y = random. nextInt (height );
Int xl = random. nextInt (12 );
Int yl = random. nextInt (12 );
G. drawLine (x, y, x + xl, y + yl );
}
// Obtain the random ID 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 the image
G. setColor (new Color (20 + random. nextInt (110), 20 + random. nextInt (110), 20 + random. nextInt (110 )));
// The Color of the called function is the same. It may be because the seed is too close and can only be directly generated.
G. drawString (rand, 13 * I + 6, 16 );
}
// Save the authentication code to the SESSION
Session. setAttribute ("rand", sRand );
// The image takes effect
G. dispose ();
// Output the image to the page
ImageIO. write (image, "JPEG", response. getOutputStream ());
Out. clear ();
%>
Page reference:
Copy codeThe Code is as follows: <td width = "62" valign = "bottom"> <div align = "left"> </div> </td>
JS:
Copy codeThe Code is as follows: this. src = 'index/image. jsp? '+ Math. random ();
Obtain the verification code upon login:
Copy codeThe Code is as follows: String randb = (String) request. getSession (). getAttribute ("rand ");