Session details, learning Session, this article is enough (including the underlying analysis and use)

        Description: The session is introduced below. We use the knowledge of browser capture and http. If you don't know it, please understand it briefly.http introduction , http request, http response . Because cookie and session are a pair of "good brothers", we introduce session also to use cookie, if you don't know cookie, please check cookie details . Without further ado, let's get started.


what is session

        Session is called "session control" in network applications, and is a special object created by the server to save the user state. In short, a session is an object that stores information. 

what is the use of session

        Let's think about a problem first. This problem is that when we visit the shopping website, we are not logged in, but we can still add products to the shopping cart and view them. When we exit the browser and then open the browser to view , the shopping cart still has the products we selected, how to achieve this?

        Sure, we can use cookies, but can cookies hold large amounts of data? At this time, we need a new technology, Session . Session is a special object stored on the server side, the server will create a unique session for each browser (client). This session is shared by the server, and each browser (client) is exclusive. We can store data in the session to achieve data sharing.

This is a simple schematic diagram of the session

 Session storage format

        A session is similar to a Map, which can store multiple key-value pairs, which are stored by key-value. key must be a string and value is an object.

Session underlying implementation mechanism

        Session is unique to each browser (client), how is this implemented? In fact, when visiting a website, a cookie is often carried in the HTTP request. The name of this cookie is JSESSIONID, and this JSESSIONID represents the id of the session, which is created by the server and is unique. When the server uses the session, it will perform different operations according to the JSESSIONID.

        Below I use the diagram to illustrate

         When we use the session on the server, we must first obtain the session, which is obtained through JSESSIONID. Of course, there were already many situations. For example, the browser does not carry the JSESSIONID when accessing, and the session corresponding to the JSESSIONID carried by the browser does not exist (or fails). The above figure illustrates some situations in which the server obtains the session.

Browser capture package to view 

        Below I created a simple server, the server operates the session, and sees how the JSESSION in the browser is carried. The access address of my server is localhost:8080/cs/createSession. At first, the browser is a cookie without JSESSIONID, and the server needs to operate the session. After we visit, we will see what the server returns.

 This is the request header we see after capturing the packet

 Here is our response header

        We found that if the browser accesses the server, if the JSESSIONID is not carried, the server will create a session and return the JSESSIONID of this session to the browser. 

        Next, we visit the same address again, this time with JSESSIONID. 

request headers we send 

 The response headers we see in the packet capture

         We found that if the browser carries the JSESSIONID, the browser will carry it when visiting. When the server uses the session, it will use the session of this JSESSIONID.

        Of course, the above is a normal situation, that is, there is a session corresponding to JSESSIONID on the server side, and it has not expired. Below, I changed the JSESSIONID of the request sent by the browser to 2 letters, and the browser request and the server returned the above. 

request header 

response header

        This time, we found that both the request header and the response header carry JSESSIONID, because the JSESSIONID carried by the browser does not have a corresponding session on the server side, or the session has expired. So the server creates a new session and returns the new JSESSIONID to the browser. 

         Viewing JSESSIONID through the underlying implementation mechanism of session and http packet capture, you should already have a clear understanding of the principle of session. Let me introduce the common methods of session (based on java).

 Common methods of session

  • resquest.getSession(): Get the session corresponding to the requesting browser (client). If not, then create a new session that should be. If so, return the corresponding session
  • setAttribute(String s, Object o): store attributes in session
  • getAttribute(String s): Get the attribute corresponding to s from the session
  • removeAttribute(String s): delete the attribute corresponding to s from the session
  • getId(): get the id corresponding to the session
  • invalidate(): invalidate the session immediately
  • setMaxInactiveInterval(int i): Set the maximum valid time of the session. Note that this valid time is the maximum time between two accesses to the server. If the maximum valid time is exceeded, the session will be invalid.

session instance application

        We use session to implement a login authentication function. If the user logs in successfully, then we do not need to log in to visit the main page within 1 day. We use session to achieve.

        I created a html page, 2 servlets to achieve this function. code show as below

html page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
    <base href="/cs/">
</head>
<body>
<form action="checkLogin" method="post">
    用户名:<input type="text" name="username" /><br/>
    密 码:<input type="password" name="password" /><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

        This html is a simple login page.

This servlet is used to determine whether the username and password are the ones we specified 

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/checkLogin")
public class CheckServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //判断用户名和密码是否为我们设置的密码
        if (username.equals("tom") && password.equals("tom123")){
            //得到session
            HttpSession session = request.getSession();
            //设置最长访问间隔时间
            session.setMaxInactiveInterval(60*60*24);
            //将用户名存入session
            session.setAttribute("username",username);
            //重定向到主页面
            response.sendRedirect(request.getContextPath()+"/mainPage");
        }else {
            //设置MIME类型和编码
            response.setContentType("text/html;charset=utf-8");
            //写回提示信息
            PrintWriter writer = response.getWriter();
            writer.write("<h1>账号或密码错误</h1>");
            writer.write("<h3><a href='"+request.getContextPath()+"/login.html'>点击重新登录</a></h3>");
        }
    }

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

This servlet is our main page

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/mainPage")
public class MainServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应的MIME类型和编码
        response.setContentType("text/html;charset=utf-8");
        //得到session
        HttpSession session = request.getSession();
        //取出用户名
        Object username = session.getAttribute("username");
        PrintWriter writer = response.getWriter();
        //判断用户名是否存在
        if (username != null){
            //在一天内登录过,无需再次登录
            writer.write("<h1>用户:"+username+" 登录成功</h1>");
        }else {
            //没有登录,或者登录间隔大于1天。重定向到登陆界面
            response.sendRedirect(request.getContextPath()+"/login.html");
        }
    }

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

code test

       As soon as we come, we directly access the main interface.

         The discovery server found that we were not logged in and redirected directly to the login interface. Now let's log in, enter the username and password we set, tom and tom123 respectively

        We have successfully logged in, so now we close the browser, then reopen it, and directly access the main interface to see if we can access it directly.

         We found that the login was successful, and there was no redirection, because we have already logged in, and we don't need to log in again within a day. Our function is implemented.


Comparison of session and cookie 

  • The cookie is saved on the client side, and the session is saved on the server side
  • The cookie acts on the path indicated by him (the url must contain the path), and the scope is small. Session represents a session between the client and the server. Data can also be shared when the web page is jumped. The scope is this session, and the client will not disappear when the client is closed. It will last until the end of the session life cycle we set (default 30min)
  • We use the session requires the cooperation of cookies. cookie is used to carry JSESSIONID
  • The amount of data stored in the cookie is smaller, and the session can store more information.
  • Because cookies are stored on the client side, they are less secure than sessions.
  • Since the session is stored on the server, when there are many clients accessing it, a large number of sessions will definitely be generated, and these sessions will affect the performance of the server.

Summarize

        A session is a special object stored in the server. Data sharing can be achieved through the session. The session has a JSESSIONID, which is the unique identifier of the session, and can be used to find the session. Session is at the session level. For each client, it exclusively owns the session it owns. When we use the session to perform page jumps, the server can use the session to share data. The session is controlled by the server. The creation and destruction of sessions are managed by the server. The server will create a session for each client.

        The above is my explanation of the session. If you think it is good, please like and comment to support it! ! !

Guess you like

Origin blog.csdn.net/m0_51545690/article/details/123384986