The Code is as follows:
Image. jsp
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,
Java. util. *, javax. imageio .*"%> <%!// Obtain the random color in a given rangeColor getRandColor (IntFc,IntBc) {Random random =NewRandom ();If(Fc> 255) {fc = 255 ;}If(Bc> 255) {bc = 255 ;}IntR = fc + random. nextInt (bc-fc );IntG = fc + random. nextInt (bc-fc );IntB = fc + random. nextInt (bc-fc );Return NewColor (r, g, B) ;}%> <%// Set the page not to cacheResponse. setHeader ("Pragma","No-cache"); Response. setHeader ("Cache-Control","No-cache"); Response. setDateHeader ("Expires", 0 );// Create an image in memoryIntWidth = 60, height = 20; BufferedImage image =NewBufferedImage (width, height, BufferedImage. TYPE_INT_RGB );// Obtain the image ContextGraphics g = image. getGraphics ();// Generate a random classRandom random =NewRandom ();// Set the background colorG. setColor (getRandColor (200,250); g. fillRect (0, 0, width, height );// Set the fontG. setFont (NewFont ("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(IntI = 0; I <155; I ++ ){IntX = random. nextInt (width );IntY = random. nextInt (height );IntXl = random. nextInt (12 );IntYl = random. nextInt (12); g. drawLine (x, y, x + xl, y + yl );}// Obtain the random ID code (4 digits)String sRand ="";For(IntI = 0; I <4; I ++) {String rand = String. valueOf (random. nextInt (10); sRand + = rand;// Display the authentication code to the image // 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. setColor (NewColor (20 + random. nextInt (110), 20 + random. nextInt (110 ),
20 + random. nextInt (110); g. drawString (rand, 13 * I + 6, 16 );}// Save the authentication code to the SESSIONSession. setAttribute ("Captcha", SRand );// The image takes effectG. dispose ();// Output the image to the pageImageIO. write (image,"JPEG", Response. getOutputStream ());Out. clear (); out = pageContext. pushBody ();%>Do not miss the red part; otherwise, an error will be reported: getOutputStream () has already been calledFor ThisResponseAdd: <Img Src="Include/image. jsp">