JSP processing page:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding= "Utf-8"Import= "Java.awt.*,java.util.*,javax.imageio.*,java.awt.image.*"%><%Response.setheader ("Cache-control", "No-cache"); //Create an image in memory, set the width and height of the image intWidth=60,height=20; //instantiate Java.awt.image.BufferedImage, which is the function of accessing the image data bufferBufferedImage image=NewBufferedImage (WIDTH,HEIGHT,BUFFEREDIMAGE.TYPE_INT_RGB);//Third parameter: Use the color mode for RGB mode//Get brushesGraphics g=Image.getgraphics (); //Set Background color RGBG.setcolor (NewColor (200,200,200)); G.fillrect (0, 0, width, height); //randomly generated verification code (4 digits)Random rnd=NewRandom (); intRandnum=rnd.nextint (8999) +1000;//returns a pseudo-random number, which is an int value that is evenly distributed between 0 (inclusive) and the specified value (not included) from this random number generator sequence. String ranstr=string.valueof (Randnum); //Save the Verification code to the sessionSession.setattribute ("RandomString", RANSTR); //display the captcha in the imageG.setcolor (color.red); G.setfont (NewFont ("", font.plain,20));//name style size of pointsg.DrawString (Ranstr, 10, 17); //randomly generate 100 interference points, so that the verification code in the image is not easily detected by other programs for(inti=0;i<100;i++){ intx=rnd.nextint (width); inty=rnd.nextint (height); G.drawoval (x, Y,1, 1); } //output image to pageImageio.write (Image, "JPEG", Response.getoutputstream ()); Out.clear (); out=pagecontext.pushbody ();%>
JSP form page:
<formAction= "form"Method= "POST">User name:<inputtype= "text"name= "username"> <BR>Password:<inputtype= "Password"name= "Password"> <BR> <inputtype= "text"name= "Code"size= " the"> <imgname= "img"src= "yanzhengma.jsp"ID= "img"onclick= "Yanzheng ()"> <ahref= "Javascript:vord (0)"onclick= "Yanzheng ()">Can't see clearly</a><BR> <inputtype= "Submit"value= "Submit"></form><Scripttype= "Text/javascript"> functionYanzheng () {img.src=img.src+'?'+Math.random (); }</Script>
Servlet Processing page:
protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.setcharacterencoding ("Utf-8"); String Yanzheng=request.getparameter ("Code"); String username=request.getparameter ("username"); String Password=request.getparameter ("Password"); if(Request.getsession (false). getattribute ("Numberstr")! =NULL) {String numberstr= (String) request.getsession (false). getattribute ("Numberstr"); if(Yanzheng.equals (numberstr)) {if(Username.equals ("admin") &&password.equals ("1234")) {response.getwriter (). println ("Congratulations on your Success"); }Else{response.getwriter (). println ("Account or Password error login failed"); } }Else{response.getwriter (). println ("Captcha Error"); } } }
Form form Implementation Verification code function