Session--Verification Code Case (Java)

Posted Jun 26, 20205 min read

Session--Verification Code Case(Java)

Blog description

The information involved in the article comes from the Internet collation and personal summary, which means personal learning and experience summary. If there is any infringement, please contact me to delete, thank you!

Case

The user enters the user name, password and verification code.

  • If the user name and password are entered incorrectly, jump to the login page and prompt:User name or password is wrong
  • If the verification code is entered incorrectly, jump to the login page and prompt:the verification code is incorrect
  • If all input is correct, jump to the homepage success.jsp, display:user name, welcome you

Ideas

Store its value in the session when generating the verification code, and then take it out for comparison when comparing

Code

index.jsp
<%--
  Created by IntelliJ IDEA.
  User:tanglei
  Date:2020/6/26
  Time:12:48 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
    <title>login</title>


    <script>
        window.onload = function(){
            document.getElementById("img").onclick = function(){
                this.src="/login_time_war_exploded/checkCode?time="+new Date().getTime();
            }
        }


    </script>
    <style>
        div{
            color:red;
        }

    </style>
</head>
<body>

<form action="/login_time_war_exploded/login" method="post">
    <table>
        <tr>
            <td>User name</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td>Verification code</td>
            <td><input type="text" name="checkCode"></td>
        </tr>
        <tr>
            <td colspan="2"><img id="img" src="/login_time_war_exploded/checkCode"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Login"></td>
        </tr>
    </table>


</form>


<div><%=request.getAttribute("cc_error") == null? "":request.getAttribute("cc_error")%></div>
<div><%=request.getAttribute("login_error") == null? "":request.getAttribute("login_error")%></div>

</body>
</html>
success.jsp
<%--
  Created by IntelliJ IDEA.
  User:tanglei
  Date:2020/6/26
  Time:6:27 pm
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1><%=request.getSession().getAttribute("user")%>, welcome you</h1>
</body>
</html>
Verification code checkCode.java
package cn.guizimo.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 100;
        int height = 50;
        //Create a picture object
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

        //beautify
        Graphics g = image.getGraphics();
        //background
        g.setColor(Color.PINK);
        g.fillRect(0, 0, width, height);
        //frame
        g.setColor(Color.BLUE);
        g.drawRect(0, 0, width-1, height-1);

        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random ran = new Random();
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i <= 4; i++) {
            int index = ran.nextInt(str.length());
            char ch = str.charAt(index);
            sb.append(ch);
            g.drawString(ch+"",width/5*i,height/2);
        }
        String checkCode_session = sb.toString();
        //Store verification code in session
        req.getSession().setAttribute("checkCode_session",checkCode_session);

        //Interference line
        g.setColor(Color.GREEN);
        for(int i = 0; i <10; i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }


   //Output pictures to the browser
        ImageIO.write(image, "jpg", resp.getOutputStream());

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
login.java
package cn.guizimo.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Set request encoding
        req.setCharacterEncoding("utf-8");
        //2. Get parameters
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");
        //3. Get the generated verification code first
        HttpSession session = req.getSession();
        String checkCode_session =(String) session.getAttribute("checkCode_session");
        //Delete the verification code stored in the session
        //session.removeAttribute("checkCode_session");
        //3. First determine whether the verification code is correct
        if(checkCode_session!= null && checkCode_session.equalsIgnoreCase(checkCode)){
            //Ignore case comparison
            //The verification code is correct
            //Determine whether the user name and password are consistent
            if("zhangsan".equals(username) && "123".equals(password)){//You need to call UserDao to query the database
                //login successful
                //Store information, user information
                session.setAttribute("user",username);
                //Redirect to success.jsp
                resp.sendRedirect(req.getContextPath()+"/success.jsp");
            }else{
                //Login failed
                //Store prompt information to request
                req.setAttribute("login_error","wrong username or password");
                //Forward to login page
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }


        }else{
            //The verification code is inconsistent
            //Store prompt information to request
            req.setAttribute("cc_error","Verification code error");
            //Forward to login page
            req.getRequestDispatcher("/login.jsp").forward(req,resp);

        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

Test

login interface

image-20200626181430294

Verification code error

image-20200626181632252

username or password is wrong

image-20200626182552928

login successful

image-20200626182919028

thank

Dark Horse Programmer

Universal Network

And hardworking self