TIPS: Examples of Java's Random verification code Function

Source: Internet
Author: User

The random code function added to many system registration, logon, or publishing information modules is to avoid the use of automatic registration or publishing programs.

The verification code is to randomly select some characters to display on the page in the form of images. If you submit a verification code, you must submit the characters on the image at the same time, if the submitted characters are different from those saved by the server session, the submitted information is considered invalid. To avoid automatic program analysis and resolution of images, some interference lines or characters are randomly generated on the images, which increases the difficulty of automatic recognition.

Here, we use servlet to implement Random verification codes.

 

Package COM. servlet; import Java. AWT. color; import Java. AWT. font; import Java. AWT. graphics2d; import Java. AWT. image. bufferedimage; import Java. util. random; 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. s Ervlet. HTTP. httpsession;/*** generate a random Verification Code * @ author bitiliu **/public class validatecodeservlet extends httpservlet {Private Static final long serialversionuid = 1l; // The width of the Verification Code image. Private int width = 60; // height of the Verification Code image. Private int Height = 20; // number of characters in the verification code private int codecount = 4; private int x = 0; // font height private int fontheight; private int Codey; char [] codesequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'h ', 'I', 'J', 'k', 'l', 'M', 'n', 'O', 'P', 'Q', 'R ', 'S ', 't', 'U', 'V', 'w', 'x', 'y', 'z', '0', '1 ', '2', '3', '4', '5', '6', '7', '8', '9 '}; /*** initialize and verify image attributes */Public void Init () throws servletexception {// from we B. get the initial information in XML // width string strwidth = This. getinitparameter ("width"); // height string strheight = This. getinitparameter ("height"); // Number of Characters String strcodecount = This. getinitparameter ("codecount"); // convert the configuration information to a value. Try {If (strwidth! = NULL & strwidth. Length ()! = 0) {width = integer. parseint (strwidth);} If (strheight! = NULL & strheight. Length ()! = 0) {Height = integer. parseint (strheight);} If (strcodecount! = NULL & strcodecount. Length ()! = 0) {codecount = integer. parseint (strcodecount) ;}} catch (numberformatexception e) {}x = width/(codecount + 1); fontheight = height-2; Codey = height-4 ;} protected void Service (httpservletrequest req, httpservletresponse resp) throws servletexception, Java. io. ioexception {// define the image buffer bufferedimage buffimg = new bufferedimage (width, height, bufferedimage. type_int_rgb); graphics2d G = buffimg. creategraphi CS (); // create a random number generator class random = new random (); // fill the image with white G. setcolor (color. white); G. fillrect (0, 0, width, height); // create a font. The font size depends on the Image Height. Font font = new font ("fixedsys", Font. Plain, fontheight); // set the font. G. setfont (font); // draw a border. G. setcolor (color. black); G. drawrect (0, 0, width-1, height-1); // generates 160 random interference lines, making it difficult for other programs to detect the authentication code in the image. G. setcolor (color. black); For (INT I = 0; I <160; I ++) {int x = random. nextint (width); int y = random. nextint (height); int XL = random. nextint (12); int yl = random. nextint (12); G. drawline (X, Y, x + XL, Y + yl);} // randomcode is used to save the randomly generated Verification Code, so that the user can perform verification after logon. Stringbuffer randomcode = new stringbuffer (); int Red = 0, Green = 0, Blue = 0; // a random codecount verification code is generated. For (INT I = 0; I <codecount; I ++) {// obtain the randomly generated verification code number. String strrand = string. valueof (codesequence [random. nextint (36)]); // generate a random color component to construct the color value, so that the color value of each output number will be different. Red = random. nextint (255); Green = random. nextint (255); Blue = random. nextint (255); // draw the verification code into the image with a random color. G. setcolor (new color (red, green, blue); G. drawstring (strrand, (I + 1) * X, Codey); // combine the four random numbers. Randomcode. append (strrand);} // Save the four-digit verification code to the session. Httpsession session = Req. getsession (); Session. setattribute ("validatecode", randomcode. tostring (); // disable image caching. Resp. setheader ("Pragma", "No-Cache"); resp. setheader ("cache-control", "No-Cache"); resp. setdateheader ("expires", 0); resp. setcontenttype ("image/JPEG"); // output the image to the servlet output stream. Servletoutputstream SOS = resp. getoutputstream (); ImageIO. Write (buffimg, "Jpeg", SOS); SOS. Close ();}}

Servlet needs to be declared in Web. xml

 

<servlet> <servlet-name>ValidateCodeServlet</servlet-name> <servlet-class>com.servlet.ValidateCodeServlet</servlet-class> <init-param>  <param-name>width</param-name>  <param-value>200</param-value> </init-param> <init-param>  <param-name>height</param-name>  <param-value>80</param-value> </init-param> <init-param>  <param-name>codeCount</param-name>  <param-value>5</param-value> </init-param>  </servlet>  <servlet-mapping>    <servlet-name>ValidateCodeServlet</servlet-name>    <url-pattern>/validateCodeServlet</url-pattern>     </servlet-mapping>

The page to be referenced can be written as follows:

 

<ccid_file values="validateCodeServlet" width="100/" />

After submitting the verification code, the user can compare the verification code entered by the user with the string saved in the session to verify the result.

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.