Package CMR. test;
Import java. AWT. color;
Import java. AWT. Font;
Import java. AWT. graphics2d;
Import java. AWT. image. bufferedimage;
Import java. util. Random;
Import javax. ImageIO. ImageIO;
Import javax. servlet .*;
Import java. Io .*;
Import javax. servlet. http .*;
Public class randomcodeservlet extends httpservlet
{
// The image width of the verification code.
Private int width = 60;
// Height of the Verification Code image.
Private int Height = 20;
Protected void Service (httpservletrequest req, httpservletresponse resp)
Throws servletexception, java. Io. ioexception
{
Bufferedimage buffimg = new bufferedimage (width, height,
Bufferedimage. type_int_rgb );
Graphics2d G = buffimg. creategraphics ();
// Create a random number generator class.
Random random = new random ();
G. setcolor (color. White );
G. fillrect (0, 0, width, height );
// Create a font. The font size depends on the Image Height.
Font font = new font ("Times New Roman", Font. Plain, 18 );
// Set the font.
G. setfont (font );
// Draw a border.
G. setcolor (color. Black );
G. drawrect (0, 0, width-1, height-1 );
// Generates 160 random interference lines, making it difficult for other programs to detect the authentication codes in the image.
G. setcolor (color. Gray );
For (INT I = 0; I <10; 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 );
}
// Randomcode is used to save the randomly generated verification code so that the user can perform verification after logon.
Stringbuffer randomcode = new stringbuffer ();
Int Red = 0, Green = 0, Blue = 0;
// A four-digit verification code is randomly generated.
For (INT I = 0; I <4; I ++)
{
// Obtain the Random verification code number.
String strrand = string. valueof (random. nextint (10 ));
// Generate a random color component to construct the color value, so that the color values of each output number are different.
Red = random. nextint (200 );
Green = random. nextint (200 );
Blue = random. nextint (200 );
// Generate random height between 13 and height
Float imght = 0;
While (imght <= 12 ){
Imght = float. parsefloat (string. valueof (random. nextint (height )));
}
// Use a random color to draw the verification code into the image.
G. setcolor (new color (red, green, blue ));
G. drawstring (strrand, 13 * I + 6, imght );
// Combine the four random numbers.
Randomcode. append (strrand );
}
// Save the four-digit verification code to the session.
Httpsession session = Req. getsession ();
Session. setattribute ("randomcode", randomcode. tostring ());
// Disable image caching.
Resp. setheader ("Pragma", "No-Cache ");
Resp. setheader ("cache-control", "No-Cache ");
Resp. setdateheader ("expires", 0 );
Resp. setcontenttype ("image/JPEG ");
// Output the image to the servlet output stream.
Servletoutputstream SOS = resp. getoutputstream ();
ImageIO. Write (buffimg, "Jpeg", SOS );
SOS. Close ();
}
}