Java Implementation Random Verification code function example

Source: Internet
Author: User
Tags integer stringbuffer

Many systems now register, log in or publish information modules are added to the random code function, is to avoid automatic registration program or the use of automatic publishing programs.

The verification code is actually randomly select some characters to display in the form of a picture on the page, if you want to submit the operation of the same time you need to submit the characters on the picture at the same time, if the submitted characters and server session Save the difference, the submission information is considered invalid. In order to avoid automated program analysis and resolution of pictures, usually randomly generated in the picture some interference lines or distorted characters to increase the difficulty of automatic recognition.

Here, we use the servlet to implement the random authentication code.

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.servlet.http.HttpSession;


/**


* Generate random verification code


* @author Bitiliu


*


*/


public class Validatecodeservlet extends HttpServlet


{


private static final long serialversionuid = 1L;


//Verify code picture width.


private int width=60;


//Verify the height of the code picture.


private int height=20;


//Authentication Code characters number


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 validation picture properties


   */


public void Init () throws Servletexception


{


//Get initial information from Web.xml


//Width


String strwidth=this.getinitparameter ("width");


//Height


String strheight=this.getinitparameter ("height");


//number of characters


String strcodecount=this.getinitparameter ("Codecount");





//Convert the configured information to numeric


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 {





//Definition image buffer


bufferedimage buffimg = new BufferedImage (


width, height,bufferedimage.type_int_rgb);


graphics2d g = buffimg.creategraphics ();


//Create a random number generator class


Random Random = new Random ();


//Fill the image with white


G.setcolor (Color.White);


g.fillrect (0, 0, width, height);


//Create font, the size of the font should be based on the height of the picture.


font font = new Font ("Fixedsys", Font.plain, Fontheight);


//Set font.


G.setfont (font);


//Draw a border.


G.setcolor (Color.Black);


G.drawrect (0, 0, width-1, height-1);


//Randomly generated 160 interference lines, so that the authentication code in the image is not easily detected by other programs.


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 randomly generated CAPTCHA code so that the user can authenticate after logging in.


StringBuffer randomcode = new StringBuffer ();


int red = 0, green = 0, blue = 0;


//Random code that produces codecount numbers.


for (int i = 0; i < Codecount; i++) {


//Get the randomly generated verification code number.


String Strrand = string.valueof (Codesequence[random.nextint (36)]);


//produces a random color component to construct a color value so that the color values of each digit of the output will be different.


red = random.nextint (255);


Green = Random.nextint (255);


blue = random.nextint (255);


//The CAPTCHA is drawn into the image with a randomly generated color.


G.setcolor (New Color (red, green, blue));


g.drawstring (Strrand, (i + 1) * x, Codey);


//The resulting four random numbers are grouped together.


randomcode.append (Strrand);


  }


//Saves the four-digit CAPTCHA to the session.


HttpSession session = Req.getsession ();


Session.setattribute ("Validatecode", randomcode.tostring ());


//Prohibit image caching.


Resp.setheader ("Pragma", "No-cache");


Resp.setheader ("Cache-control", "No-cache");


Resp.setdateheader ("Expires", 0);


Resp.setcontenttype ("Image/jpeg");


//Outputs the image to the servlet output stream.


Servletoutputstream SOS = Resp.getoutputstream ();


Imageio.write (buffimg, "JPEG", SOS);


Sos.close ();


}


}

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.