Parse Java to achieve the function of random verification code method

  • 2020-04-01 01:56:58
  • OfStack

Now many systems of registration, login or release information modules are added to the random code function, is to avoid the use of automatic registration procedures or automatic release procedures.
Captcha is actually to randomly select some characters to be displayed on the page in the form of a picture. If the characters on the picture need to be submitted at the same time of the submission operation, if the submitted characters are different from those stored in the server session, the submission information will be considered invalid. In order to avoid the automatic program analysis of the image, it usually generates some random interference lines on the picture or distorts the characters, which increases the difficulty.      
We can use servlets to implement random captcha.

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;
    
    public class ValidateCodeServlet extends HttpServlet
    {
    private static final long serialVersionUID = 1L;
    //Width of captcha image.
    private int width=60;
    //Captcha image height.
    private int height=20;
    //Number of verification code characters
    private int codeCount=4;
    private int x=0;
    //The 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' };
    
    public void init (a)  throws ServletException
    {
    //Get the initial information from web.xml
    //The width of the
    String strWidth=this.getInitParameter ( "width" ); 
    //highly
    String strHeight=this.getInitParameter ( "height" ); 
    //The number of characters
    String strCodeCount=this.getInitParameter ( "codeCount" ); 
    //Converts the configured information to a numeric 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 image buffer
    BufferedImage buffImg = new BufferedImage ( 
    width, height,BufferedImage.TYPE_INT_RGB ); 
    Graphics2D g = buffImg.createGraphics (a); 
    //Create a random number generator class
    Random random = new Random (a); 
    //Fill the image with white
    g.setColor ( Color.WHITE ); 
    g.fillRect ( 0, 0, width, height ); 
    // Create the font, the font size should be based on the picture highly To order. 
    Font font = new Font ( "Fixedsys", Font.PLAIN, fontHeight ); 
    //Set the font.
    g.setFont ( font ); 
    //Picture frame.
    g.setColor ( Color.BLACK ); 
    g.drawRect ( 0, 0, width - 1, height - 1 ); 
    //Random generation of 160 interference lines, so that the authentication code in the image is not easy to be 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 the randomly generated verification code for users to verify after login.
    StringBuffer randomCode = new StringBuffer (a); 
    int red = 0, green = 0, blue = 0;
    //Generate the captcha for the codeCount number at random.
    for  ( int i = 0; i < codeCount; i++ )  {
    //The randomly generated captcha Numbers are obtained.
    String strRand = String.valueOf ( codeSequence[random.nextInt ( 36 ) ] ); 
    //Generate random color components to construct the color value, so that each number output will have a different color value.
    red = random.nextInt ( 255 ); 
    green = random.nextInt ( 255 ); 
    blue = random.nextInt ( 255 ); 
    //Draw the captcha to the image with randomly generated colors.
    g.setColor ( new Color ( red, green, blue )); 
    g.drawString ( strRand,  ( i + 1 )  * x, codeY ); 
    //Combine the four generated random Numbers.
    randomCode.append ( strRand ); 
    }
    //Save the four-digit verification code to Session.
    HttpSession session = req.getSession (a); 
    session.setAttribute ( "validateCode", randomCode.toString ()); 
    //Image caching is disabled.
    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 (a); 
    ImageIO.write ( buffImg, "jpeg", sos ); 
    sos.close (a); 
    }
    }

You need to declare the servlet 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>


Related articles: