First, Verification Code tool class
Public classCheckcodeutil {PrivateBufferedImage image;//Image PrivateString str;//Verification Code PrivateRandomnumutil () {init (); } //Get Instance Public Staticrandomnumutil Instance () {return NewRandomnumutil (); } //Get Pictures Publicrenderedimage getImage () {return This. Image; } //get 6-bit random verification code PublicString getstr () {return This. Str; } Private voidinit () {//create images in memory, set the width and height of the image intwidth = +, height = 30; BufferedImage Image=Newbufferedimage (width, height, bufferedimage.type_int_rgb); //Get the graphics contextGraphics g =Image.getgraphics (); //Generating Random classesRandom random =NewRandom (); //Set Background colorG.setcolor (Getrandcolor (200, 250)); G.fillrect (0, 0, width, height); //Set FontG.setfont (NewFont ("Times New Roman", Font.plain, height-4)); //randomly generates 155 lines of interference so that the authentication code in the image is not easily detected by other programsG.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); } //randomly generated authentication 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 imageG.setcolor (NewColor (+ random.nextint, + random.nextint), + random.nextint (110))); //The call function comes out with the same color, possibly because the seed is too close, so it can only be generated directlyg.DrawString (Rand, * i + 26, 25); } //Assignment Verification Code This. str =SRand; //Image EffectiveG.dispose (); This. Image =image; } //get random colors for a given range PrivateColor Getrandcolor (intFcintBC) {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); }}
Second, obtain the verification code
@RequestMapping (value = "/check/code") Public voidInit (httpservletrequest request, httpservletresponse response) {Try{//generate a Captcha instanceCheckcodeutil util =checocodeutil.instance (); Request.getsession (). SetAttribute ("Sessioncode", Util.getstr ()); Servletoutputstream Stream=Response.getoutputstream (); Imageio.write (Util.getimage (),"JPEG", stream); Stream.flush (); Stream.Close (); } Catch(IOException e) {System.out.println ("Verification Code generation failed"); }}
Third, the page
<src= "Check/code" ID= "imgobj" alt= "Captcha " >
Four, the effect
Java Implementation Verification Code