Java Web (4) Code Implementation of One-Time Verification Code

In fact, the logic of implementing the code is very simple, really super super simple.

     1. On the login page, login.jsp will use the tag <img src="xxx"> to draw the captcha image and give it the url of the captcha image

     2. There are two servlets on the server side, one is the VerifyCodeServlet used to draw the verification code picture, and the other is the LoginServlet to verify whether the verification code is correctly written or repeatedly submitted when logging in

     3. In VerifyCodeServlet, store the four letters of the verification code in the session, and then in LoginServlet, compare the verification code submitted in the request with the one in the session, if it is correct, the verification is successful, and the The verification code is deleted, why should it be deleted? Ensure that the data in the session can only be used once to prevent repeated submission of data. If it is incorrect, use request to save the error information, and then forward the request to the login page to display the error information. If the data in the session is found to be null, it means that it is repeated After submitting the data, the error message is returned to the login page in the same way.

     The difficulty lies in: the code implementation of VerifyCodeServlet. I am not very familiar with the drawing code.


login.jsp

 

copy code

<body>
            <%
        String msg = (String)request.getAttribute("msg");
        if(msg != null){
            out.print(msg);
        }
    %>
    
    <form action="/test01/LoginServlet" method="post">
        用户名:<input type="text" name="username" /> <br/>
        验证码:<input type="text" name="verifyCode" size="5" /> <img src="/test01/VerifyCodeServlet" /> <br/>
        <input type="submit" value="提交"/>
    </form>
  </body>

copy code

 

 

VerifyCodeServlet.java

 

copy code

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         //declare verification code
        int width = 60;
        int height = 30;
        String data = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghijklmnpqrstuvwxyz"; //A dictionary of random characters, in which 0, o, 1, I and other indistinguishable characters are best not to be used
        Random random = new Random();//Random class
        //1 Create image data cache area (core class)
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//Create a color image
        //2 Get the artboard (picture, ps layer), the painting object.
        Graphics g = image.getGraphics();
        //3 Select the color, draw a rectangle 3, and step 4 is to draw an effect with inner and outer borders
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);
        //4 white rectangles
        g.setColor(Color.WHITE);
        g.fillRect(1, 1, width-2, height-2);
        
        /**1 Provide a cache area, in order to store 4 random characters for storing in session */
        StringBuilder builder = new StringBuilder();
        
        //5 Randomly generate 4 characters
                    //set font color
        g.setFont(new Font("宋体", Font.BOLD&Font.ITALIC, 20));
        for(int i = 0 ; i < 4 ;i ++){
            //random color
            g.setColor(new Color(random.nextInt(255),random.nextInt(255), random.nextInt(255)));
            
            //random character
            int index = random.nextInt(data.length());
            String str = data.substring(index, index + 1);
            
            /**2 cache*/
            builder.append(str);
            
            //write
            g.drawString(str, (width / 6) * (i + 1) , 20);                     
        }
        //Draw noise points in the picture, so that the picture is not so easy to distinguish
        for(int j=0,n=random.nextInt(100);j<n;j++){
            g.setColor(Color.RED);
            g.fillRect(random.nextInt(width),random.nextInt(height),1,1);//Random noise points
        }

        
        /**3 Get random data and save the session*/
        String tempStr = builder.toString();
        request.getSession().setAttribute("sessionCacheData",tempStr);
        
        
        //.. Generate a picture and send it to the browser -- equivalent to downloading
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

copy code

 

 

LoginServlet.java

 

copy code

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1 Get the verification code entered by the user
        String verifyCode = request.getParameter("verifyCode");
        //2 Get the server session to store the data, if not return null
        String sessionCacheData = (String) request.getSession().getAttribute("sessionCacheData");
        // *Remove the server cached session data
        request.getSession().removeAttribute("sessionCacheData");
        // ** Check if the server exists
        if(sessionCacheData == null){
            request.setAttribute("msg", "Please do not submit again");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        //3 compare
        if(! sessionCacheData.equalsIgnoreCase(verifyCode)){
            //User input error
            // * Store the request scope
            request.setAttribute("msg", "Incorrect verification code input");
            // * Request forwarding
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            
            return;
        }
        
        //...... login operation

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

copy code

 

 

Effect picture:

    

    When the verification code is wrong:

      

Notice:

    If you want to copy the code, you need to change the urls. Yours must be different from mine, and the access path of the servlet set by some people is also different, so you only need to copy the key code to copy.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325816607&siteId=291194637