A complete servlet + Ajax Verification Code

Source: Internet
Author: User

Servlet for generating image streams

Package COM. jimo. tool; <br/> Import Java. AWT. color; <br/> Import Java. AWT. font; <br/> Import Java. AWT. graphics2d; <br/> Import Java. AWT. image. bufferedimage; <br/> Import Java. util. random; </P> <p> Import javax. imageIO. imageIO; <br/> Import javax. servlet. servletexception; <br/> Import javax. servlet. servletoutputstream; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequ Est; <br/> Import javax. servlet. HTTP. httpservletresponse; <br/> Import javax. servlet. HTTP. httpsession; </P> <p>/** <br/> * package name: COM. skcc. sample. action <br/> * file name: verifycodeservlet. java <br/> * Author: Administrator <br/> * Date: 2008-9-4 <br/> * description: verifycodeservlet <br/> */<br/> public class verifycodeservlet extends httpservlet {</P> <p>/** <br/> * width of the Verification Code image. <Br/> */<br/> private int width = 60; </P> <p>/** <br/> * Height of the Verification Code image. <Br/> */<br/> private int Height = 20; </P> <p>/** <br/> * number of characters in the Verification Code <br/> */<br/> private int codecount = 4; </P> <p>/** <br/> * XX <br/> */<br/> private int xx = 0; </P> <p>/** <br/> * font height <br/> */<br/> private int fontheight; </P> <p>/** <br/> * Codey <br/> */<br/> private int Codey; </P> <p>/** <br/> * codesequence <br/> */<br/> char [] codesequence = {'A', 'B ', 'C', 'D', 'E', 'F', 'G ',' H', 'I', 'J', <br/> 'k', 'l', 'M', 'n', 'O', 'P ', 'Q', 'R', 's', 't', 'U', 'V', 'w', <br/> 'x', 'y ', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8 ', '9'}; </P> <p>/** <br/> * initialize and verify image attributes <br/> */<br/> Public void Init () throws servletexception {<br/> // from the web. get the initial information in XML <br/> // width <br/> string strwidth = This. getinitparameter ("width"); <br/> // height <br/> string strheight = This. getinitparameter ("Height"); <br/> // number of characters <br/> string strcodecount = This. getinitparameter ("codecount"); </P> <p> // convert the configuration information to a value <br/> try {<br/> If (strwidth! = NULL & strwidth. Length ()! = 0) {<br/> width = integer. parseint (strwidth); <br/>}< br/> If (strheight! = NULL & strheight. Length ()! = 0) {<br/> Height = integer. parseint (strheight); <br/>}< br/> If (strcodecount! = NULL & strcodecount. Length ()! = 0) {<br/> codecount = integer. parseint (strcodecount); <br/>}< br/>} catch (numberformatexception e) {<br/> E. printstacktrace (); <br/>}</P> <p> xx = width/(codecount + 1); <br/> fontheight = height-2; <br/> Codey = height-4; </P> <p >}</P> <p>/** <br/> * @ Param req <br/> * @ Param resP <br/> *@ throws servletexception <br/> * @ throws Java. io. ioexception <br/> */<br/> protected void Serv Ice (httpservletrequest req, httpservletresponse resp) <br/> throws servletexception, Java. io. ioexception {</P> <p> // define the image buffer <br/> bufferedimage buffimg = new bufferedimage (width, height, <br/> bufferedimage. type_int_rgb); <br/> graphics2d GD = buffimg. creategraphics (); </P> <p> // create a random number generator class <br/> random = new random (); </P> <p> // fill the image in white. <br/> GD. setcolor (color. white); <br/> GD. fillr ECT (0, 0, width, height); </P> <p> // create a font. The font size depends on the Image Height. <Br/> Font font = new font ("fixedsys", Font. Plain, fontheight); <br/> // set the font. <Br/> GD. setfont (font); </P> <p> // draw a border. <Br/> GD. setcolor (color. black); <br/> GD. drawrect (0, 0, width-1, height-1); </P> <p> // generates 160 random interference lines, make it difficult for other programs to detect the authentication code in the image. <Br/> GD. setcolor (color. black); <br/> for (INT I = 0; I <1; I ++) {<br/> int x = random. nextint (width); <br/> int y = random. nextint (height); <br/> int XL = random. nextint (12); <br/> int yl = random. nextint (12); <br/> GD. drawline (X, Y, x + XL, Y + yl); <br/>}</P> <p> // randomcode is used to save the randomly generated verification code, so that the user can verify after logging on. <Br/> stringbuffer randomcode = new stringbuffer (); <br/> int Red = 0, Green = 0, Blue = 0; </P> <p> // generate a random codecount verification code. <Br/> for (INT I = 0; I <codecount; I ++) {<br/> // obtain the Random verification code number. <Br/> string strrand = string. valueof (codesequence [random. nextint (36)]); <br/> // generates a random color component to construct the color value. In this way, the color values of each output number are different. <Br/> Red = random. nextint (255); <br/> Green = random. nextint (255); <br/> Blue = random. nextint (255); </P> <p> // draw the verification code to the image with a random color. <Br/> GD. setcolor (new color (red, green, blue); <br/> GD. drawstring (strrand, (I + 1) * XX, Codey); </P> <p> // combines the four random numbers. <Br/> randomcode. append (strrand); <br/>}< br/> // Save the four-digit verification code to the session. <Br/> httpsession session = req. getsession (); <br/> session. setattribute ("validatecode", randomcode. tostring (); </P> <p> // disable image caching. <Br/> resp. setheader ("Pragma", "No-Cache"); <br/> resp. setheader ("cache-control", "No-Cache"); <br/> resp. setdateheader ("expires", 0); </P> <p> resp. setcontenttype ("image/JPEG"); </P> <p> // output the image to the servlet output stream. <Br/> servletoutputstream SOS = resp. getoutputstream (); <br/> ImageIO. write (buffimg, "Jpeg", SOS); <br/> SOS. close (); <br/>}< br/>}

 

Servlet processing result

Package COM. jimo. tool; <br/> Import Java. io. ioexception; <br/> Import Java. io. printwriter; </P> <p> Import javax. servlet. servletexception; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequest; <br/> Import javax. servlet. HTTP. httpservletresponse; </P> <p>/** <br/> * package name: COM. skcc. sample. action <br/> * file name: resultservlet. java <br/> * Author: Administrator <br/> * Date: 2008-9-4 <br/> * description: resultservlet <br/> */<br/> public class resultservlet extends httpservlet {</P> <p>/** <br/> * The doget method of the servlet. <br> <br/> * this method is called when a form has its tag Value Method equals to get. <br/> * @ Param request the request send by the client to the server <br/> * @ Param response the response send by the server to the client <br/> * @ throws servletexception if an error occurred <br/> * @ throws ioexception if an error occurred <br/> */<br/> Public void doget (httpservletrequest request, httpservletresponse response) <br/> throws servletexception, ioexception {<br/> dopost (request, response ); <br/>}</P> <p>/** <br/> * The dopost method of the servlet. <br> <br/> * this method is called when a form has its tag Value Method equals to post. <br/> * @ Param request the request send by the client to the server <br/> * @ Param response the response send by the server to the client <br/> * @ throws servletexception if an error occurred <br/> * @ throws ioexception if an error occurred <br/> */<br/> Public void dopost (httpservletrequest request, httpservletresponse response) <br/> throws servletexception, ioexception {</P> <p> response. setcontenttype ("text/html; charset = UTF-8"); <br/> string validatec = request. getsession (). getattribute ("validatecode "). tostring (); <br/> string verycode = request. getparameter ("C"); <br/> printwriter out = response. getwriter (); <br/> If (verycode = NULL | "". specified signorecase (verycode) {<br/> out. println ("the verification code is blank"); <br/>}else {<br/> If (validatec. specified signorecase (verycode) {<br/> out. println ("correct Verification Code"); <br/>}else {<br/> out. println ("Incorrect verification code"); <br/>}< br/> out. flush (); <br/> out. close (); <br/>}< br/>}

 

Page call:

<Script language = "JavaScript" type = "text/JavaScript" src = "JS/checknum. js"> </SCRIPT>

 

<Input id ="Verycode"Name ="Verycode"Type ="Text"/>

<IMG id ="Imgobj"Alt =""Src ="Verifycodeservlet"Align ="Middle"/>

<Input type ="Button"Onclick = "changeimg ()" value ="Change one"/>

<Div id ="Info"Style ="Color: red; font-size: 12px; font-weight: 600"> The verification code is empty. </div>

 

Verify the JS file:

Function changeimg () {<br/> // alert ("in changeimg"); <br/> var imgsrc = document. getelementbyid ("imgobj"); <br/> // alert ("" + imgsrc); <br/> var oldsrc = imgsrc. SRC; <br/> // alert ("" + oldsrc); <br/> var newsrc = chgurl (oldsrc ); <br/> // alert ("" + newsrc); <br/> imgsrc. src = newsrc; <br/>}< br/> // timestamp <br/> // to make the image generated inconsistent each time, the browser is not allowed to read the cache, therefore, the timestamp <br/> function chgurl (URL) {<br/> // alert ("in chgurl"); <br/> VaR timestamp = (new date ()). valueof (); <br/> // alert ("" + URL); <br/> var postion = URL. indexof ("? "); <Br/> // alert (" "+ postion); <br/> If (postion> = 0) {<br/> var suburl = URL. substr (0, postion); <br/> // alert ("" + suburl); <br/> url = suburl + "? Timestamp = "+ timestamp; <br/>} else {<br/> url = URL + "? Timestamp = "+ timestamp; <br/>}< br/> return URL; <br/>}</P> <p> function isrightcode () {<br/> var code = $ ("# verycode "). ATTR ("value"); <br/> // alert (CODE); <br/> code = "C =" + code; <br/> $. ajax ({<br/> type: "Post", <br/> URL: "resultservlet", <br/> data: code, <br/> success: callback <br/>}); <br/>}</P> <p> function callback (data) {<br/>$ ("# Info" ).html (data); <br/>}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.