[Session Technology] The workflow, differences and how to use Cookie and Session

Cookie Technology

Web programs are transmitted through the HTTP protocol, and HTTP is a stateless protocol. When a client sends a request to the server, after the server returns a response, the connection is closed, and no connection information is retained on the server side. When the client sends multiple requests and requires the same request parameters, it needs to be retransmitted. In this way, if the amount of data is large, the efficiency will be greatly reduced. The emergence of Cookie is to solve this problem.

Cookie workflow:

When the client makes the first request, it carries the data and sends it to the server. The server decides which data to store in the cookie and returns the cookie to the client in the header of the response message through the response. Then the client will store it in on your browser or on your hard drive. This cookie is automatically carried to the server in every subsequent HTTP request. It is an attribute in the header, a key-value pair structure.

Disadvantages of Cookies:

The quantity is limited, the size of a single storage is limited, security cannot be guaranteed, and the browser can disable cookies. If the user disables cookies, cookies cannot be used.

Cookie life cycle:

Can be set according to needs. They are divided into temporary cookies and persistent cookies. Temporary cookies are stored in memory. When the browser is closed, the cookie automatically expires. Persistent cookies are stored in a storage directory in the browser and will not expire until the time expires. Some pages set the cookie lifetime to 0 or a negative value, so that when the browser is closed, the cookie will be eliminated immediately and the user’s information will not be recorded, making it safer. The above failures refer to the browser deleting cookies.

Cookie application scenarios:

For data with low security, data storage with a small amount of data is more suitable. It can be used to handle how the client uses the same parameter information when sending different requests.

Cookies can be used to save user login information. For example, no need to log in for 10 days, etc. If you delete the cookie, you will need to log in again next time.

Cookie practice: no need to log in for a week.

  • 1. Login front-end page code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="login" method="post">
        <div class="row">
            username
            <input type="text" name="username">
        </div>
        <div class="row">
            password
            <input type="password" name="password">
        </div>
        <div class="row">
            <input type="checkbox" id="checkbox" name="memory" value="true" checked="checked">No need to log in for one week
        </div>
        <div class="row">
            <input type="submit" value="Login">
        </div>
    </form>

    <script src="js/jquery.js"></script>
    <script>
        function show(){
            $.ajax({
                type: 'get',
                url: 'cookie',
                success: function (data,status,xhr) {
                    if(xhr.status==278){
                        console.log(data)
                        window.location.href=data.url;
                    }
                }
            });
        }
        show()
    </script>

</body>
</html>
  • 2. Main page code:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>Login successful</h1>
</body>
</html>
  • 3. Backend login operation code:
//Login operation
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String memory = req.getParameter("memory");
        //First determine whether the input is complete
        if(username==null || password==null || "".equals(username) || "".equals(password)) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("Username or password cannot be empty");
            return;
        }

        // Then determine whether the user exists. Search in the database. Omit here. It exists by default.

        // Then determine whether the user has clicked the login-free operation
        if(Boolean.valueOf(memory)) {
            //Explain that if you click on the login-free operation, you need to create a Cookie object
            //Create Cookie object
            Cookie cookie1 = new Cookie("username",username);
            Cookie cookie2 = new Cookie("password",password);
            //Set effective access path
            cookie1.setPath("/");
            cookie2.setPath("/");
            //Set Cookie time in seconds
            cookie1.setMaxAge(7*24*3600);
            cookie2.setMaxAge(7*24*3600);
            //Return Cookie information to the client
            resp.addCookie(cookie1);
            resp.addCookie(cookie2);

        }
        //Jump to the main page
        resp.sendRedirect("main.html");
    }
}
  • 4. Verify the cookie code when accessing the login page:
//Every time you visit the login page, the front-end ajax will send a request to this code (back-end)
//Check if there is a cookie
@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {
    private ObjectMapper mapper= new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get cookies first
        Cookie[] cookies = req.getCookies();
// if(cookies==null) {
// return;
// }
        if(cookies!=null & amp; & amp; cookies.length>0) {
            //Indicates that there is a cookie in the request
            for (Cookie cookie : cookies) {
                //Get username
                if("username".equals(cookie.getName())) {
                    String username = cookie.getValue();
                }
                //Get password
                if("password".equals(cookie.getName())) {
                    String password = cookie.getValue();
                }
            }

            //Match in the database. The logic here is written by myself. The matching is successful by default.

            //Redirect to main page
            Demo demo = new Demo("main.html");
            resp.setStatus(278);
            resp.setContentType("application/json");
            resp.getWriter().write(mapper.writeValueAsString(demo));
        }else {
            resp.setContentType("text/html;charset=utf8");
            resp.sendRedirect("login.html");

        }
    }
}

Session technology

Session: The user opens a browser, clicks on multiple hyperlinks, accesses multiple web resources on the server, and then closes the browser. The entire process is called a session.

Session workflow:

  • When a user requests a web page of an application, if the user does not have a session yet, a session will be created for the user, that is, a Session object will be created, which will store some information required for the user session.
  • In this way, when the user jumps to multiple web pages in the application, the variables stored in the session object will not be lost, but will persist throughout the user session. The data stored in this object will be stored in multiple web pages. Page data sharing.
  • After the session is successfully created, the server generates a sessionId and an HttpSession object, which contains some information about the user. And the server will send this sessionId to the client. At the same time, the server will also store the sessionId, corresponding user information, and user operation records on the server in a hash table structure (similar to a key-value pair inside a key-value pair, See the picture below). After the client receives the sessionId, it will be stored in the cookie. When visiting again, it will carry this cookie with the sessionId. The server will know who the user is through the sessionId. Similar to going to a barber shop for a haircut, the clerk will ask you to apply for a membership card. After you apply, the barber shop will have some of your relevant information, such as name, phone number, consumption records, balance, etc. And you will be given a membership card (equivalent to sessionId). If you take the membership card next time you get a haircut, the barber shop will know which customer is coming.

Assume that a website corresponds to a webapp, and the webapp must store a large number of users’ Session. The storage structure is a hash table-like structure. The Key value of a session is the id assigned by the server, that is, sessionId. This The value (HttpSession) corresponding to the Key is the user’s personal information, which is also organized in the form of key-value pairs.

The outer two sessionId and HttpSession are stored in the hash table in the form of key-value pairs. The sessionId exists as a key, the HttpSession object itself exists as a value, and some properties in the HttpSession object are stored in the form of key-value pairs. That is, another key-value pair is included in the value of the key-value pair.

Session life cycle:

Can be set according to needs. The default is 30 minutes. For example, if it is set to 10 minutes, when you log in to a server and the login is successful, the server will return a sessionId. There will be no HTTP requests from the client within 10 minutes after the login is successful. You will send it again after 10 minutes. An HTTP request will prompt you to log in again.

Each time you log in, the session will be re-created, and the server will return the sessionId. The client can continuously access multiple interfaces of the web program through the ID carried in the request. There are two common end-of-life cycles. The user actively clicks to log out (logout). ) or no operation has been performed for a period of time. When the user logs in again later, he or she needs to log in again, re-create the session, and the server returns a new sessionId. Cycle like this. Logging out means that the server side eliminates the session object through code logic. ID is also eliminated. When the client requests again, the ID will not match, and it will need to log in again. The same goes for periods of inactivity.

Session application scenarios:

Determine whether a user is logged in, and force the user to jump to the login page if he is not logged in. Not all users will first enter the login page and enter their password. It is possible that they forcefully enter the URL of the main interface or other operation interfaces directly in the address bar. At this time, problems will occur. We can use Session to set a session object for the user when he logs in until he logs out and the session is destroyed. And add to each page to determine whether the session object exists. If it does not exist, it will forcefully jump to the login page.

If you want to further improve security, you can add time and space display to the sessionId. You need to log in again when you are in another place, and you need to log in again after a period of time.

Code example, creating a session when logging in:

 // Log in after verification and create a session. Use this session to create user information.
        // true means search if the session exists, create a new session if it does not exist.
        HttpSession session = req.getSession(true);
        // Session saving operation. Subsequently, the session is obtained through the first parameter.
        session.setAttribute("user",user);
        // Perform redirection and jump to the main page. Redirection prevents the successful login operation from being reversed.
        resp.sendRedirect("mainInterface.html");

Code example, get session:

 // Use this method to get the user's status
        //The function of false is to return the object if there is a session, and to return null if there is no session.
        HttpSession session = req.getSession(false);
        if(session == null) {
            //Indicates that there is no session, indicating that the user is not logged in.
            //Create an empty user object
            User user = new User();
            //Response the content of the empty object in json format
            String respJson = mapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }

        //Get session object
        User user = (User) session.getAttribute("user");//The key value must be the same as the key value for saving the session above

The difference between the two:

  • Storage location is different

Cookies can be stored on the browser or local hard drive, and Sessions can only be stored on the server.

  • Security is different

Session is more secure than Cookie.

  • Different pressures on servers

Sessions occupy server resources and performance. Too many sessions will increase server pressure.

  • Storage sizes vary

Cookies are stored on the browser side. The browser has restrictions on the storage of cookies. The number generally does not exceed 20, and the data stored in a single cookie does not exceed 4k. There is no size limit for Session, it is related to the memory size of the server.

  • Storage objects are different

Session can store any type of Java object (similar to hash table structure storage), and Cookie can only store String type objects. (Stored in key-value pair structure)