Import java. AWT. color;
Import java. AWT. Font;
Import java. AWT. graphics;
Import java. AWT. image. bufferedimage;
Import java. Io. bytearrayoutputstream;
Import java. Io. ioexception;
Import javax. ImageIO. ImageIO;
Import javax. servlet. servletexception;
Import javax. servlet. servletoutputstream;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import javax. servlet. http. httpsession;
Public class check extends httpservlet ...{
Private Static int width = 60;
Private Static int Height = 20;
Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception ...{
Httpsession session = request. getsession ();
Response. setcontenttype ("image/JPEG ");
Servletoutputstream SOS = response. getoutputstream ();
// Set the browser not to cache Images
Response. setheader ("Pragma", "No-Cache ");
Response. setheader ("cache-control", "No-Cache ");
Response. setdateheader ("expires", 0 );
// Create a memory image and obtain the image Context
Bufferedimage image = new bufferedimage (width, height, bufferedimage. type_int_rgb );
Graphics G = image. getgraphics ();
// Generate the desired Verification Code
Char [] rands = This. generatecheckcode ();
// Generate an image
This. drawbackground (g );
This. drawrands (G, rands );
// Complete the image rendering process.
G. Dispose ();
// Output the image to the client
Bytearrayoutputstream Bos = new bytearrayoutputstream ();
ImageIO. Write (image, "Jpeg", Bos );
Byte [] Buf = Bos. tobytearray ();
Response. setcontentlength (BUF. Length );
Bos. Write (BUF );
Bos. Close ();
// Put the verification code into the session
Session. setattribute ("check_code", new string (rands ));
}
Private char [] generatecheckcode ()...{
// Define the verification code in the two-dimensional table
String chars = "0123456789 abcdefghijklmnopqrstuvwxyz ";
Char [] rands = new char [4];
For (INT I = 0; I <4; I ++ )...{
Int Rand = (INT) (math. Random () * 36 );
Rands [I] = chars. charat (I );
}
Return rands;
}
Private void drawrands (Graphics g, char [] rands )...{
G. setcolor (color. Black );
G. setfont (new font (null, Font. italic | font. Bold, 18 ));
G. drawstring ("" + rands [0], 1, 17 );
G. drawstring ("" + rands [0], 16, 15 );
G. drawstring ("" + rands [0], 31,18 );
G. drawstring ("" + rands [0], 46,16 );
}
Private void drawbackground (Graphics g )...{
// Draw the background
G. setcolor (new color (0 xdcdcdc ));
G. fillrect (0, 0, width, height );
For (INT I = 0; I <120; I ++ )...{
Int x = (INT) (math. Random () * width );
Int y = (INT) (math. Random () * Height );
Int Red = (INT) (math. Random () * 255 );
Int Green = (INT) (math. Random () * 255 );
Int Blue = (INT) (math. Random () * 255 );
G. setcolor (new color (red, green, blue ));
G. drawoval (X, Y, 1, 0 );
}
}
}