Session (super detailed)

Session

1. What is Session?

  1. Session is just an interface (HttpSession).
  2. Session is the session. It is a technique used to maintain an association between a client and a server.
  3. Each client has its own Session session.
  4. In the Session session, we are often used to save the information after the user logs in .

2. How to create Session and get (id number, is it new)

How to create and get a Session. Their API is the same.


The first call of request.getSession() is to create a Session. All
subsequent calls are: to get the Session object created earlier.

isNew();
Determine whether it was just created (new).
True means it was just created.
False means it was created before the acquisition.

Each session has an ID number. That is, the ID value. And this ID is unique.
getId() Get the session id value of Session.

protected void CreateOrGetSession (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    //创建或获取Session会话对象
    HttpSession session = req.getSession();
    //判断当前Session会话是否是新创建出来的
    boolean isNew = session.isNew();
    //获取Session会话的唯一标识 id
    String id = session.getId();

    resp.getWriter().write("得到的Session它的id是:" + id + "<br/>");
    resp.getWriter().write("这个Session是否是新创建的:" + isNew + "<br/>");
}
<a href="http://localhost:8080/13_cookie_session/sessionServlet?action=CreateOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a>

3. Access to Session Domain Data

setAttribute method:

/**
 * 往 Session 中保存数据
 */
protected void setAttribute (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    req.getSession().setAttribute("key1","value1");
    resp.getWriter().write("已经往 Session 中保存了数据");
}

getAttribute method:

/**
 * 获取 Session 域中的数据
 */
protected void getAttribute (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    Object attribute = req.getSession().getAttribute("key1");
    resp.getWriter().write("从 Session 中获得的 key1 的数据是:" + attribute);
}

4.Session life cycle control

public void setMaxInactiveInterval(int interval)
Set the timeout period of the Session (in seconds). If the specified time period is exceeded, the Session will be destroyed.
When the value is positive, set the timeout duration of Session.
Negative number means never timeout (rarely used, because if it is not destroyed, it will always occupy memory space)

public int getMaxInactiveInterval()
Get the timeout time of Session

public void invalidate()
makes the current Session invalidate immediately

The default timeout period of the session is 30 minutes.
Because the configuration file web.xml of the Tomcat server (C:\Users\Point.IntelliJIdea2019.3\system\tomcat\Tomcat_9_0_37_Javaweb_6\conf)
has the following configuration by default, it means that all Session timeouts under the current Tomcat server are configured The default duration of the configuration is: 30 minutes.

  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

If you want your web project's default Session timeout duration to be other durations, you can do the same configuration above in your own web.xml configuration file. You can modify the default timeout duration of all Seession in your web project.

<!--表示当前 web 工程。创建出来的所有 Session 默认是 20分钟 超时时长-->
<session-config>
    <session-timeout>20</session-timeout>
</session-config>

If you want to modify only the timeout duration of individual Session. You can use the above API: setMaxInactiveInterval(int interval) for individual settings.

​ session.setMaxInactiveInterval(int interval) sets the timeout period separately.

/**
 * Session3秒超时销毁
 */
protected void life3 (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    // 先获取 Session 对象
    HttpSession session = req.getSession();
    // 设置当前 Session 三秒后超时
    session.setMaxInactiveInterval(3);

    resp.getWriter().write("当前 Session 已经设置为三秒后超时");
}

访问 http://localhost:8080/13_cookie_session/session.html:

After clicking on Session creation and acquisition (id number, whether it is newly created), then click Session 3 seconds to time out to destroy, and then immediately click Session creation and acquisition (id number, whether it is newly created), we will find this Whether the Session is a newly created session is always displayed as: false, but if you click again after stopping for three seconds, you will find that it has become true and the id of the session has also changed.

This should start from the concept of timeout: After
setting the timeout to 3 seconds, the Session object will have a timeout timer (timeout = 3, every second -1), when timeout = 0, the Session will time out been deleted.
If the creation request is sent continuously and repeatedly, and the time interval from the last request is very short (less than 3 seconds), the timeout will be reset to 3 at this time, and it is impossible to time out.

Session timeout refers to: the maximum interval between two client requests

Set the Session to be timed out immediately:

/**
 * Session 马上被超时
 */
protected void deleteNow (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
    // 先获取 Session 对象
    HttpSession session = req.getSession();
    // 让 Session 会话马上超时
    session.invalidate();

    resp.getWriter().write("Session 已经设置为超时(无效)");
}

5. The technical inside story of the connection between the browser and the Session

Session technology, the underlying fact is Cookie-based technology to achieve. At the same time, it also explains why the Session clearly did not time out, and it timed out after closing the browser (the cookie created, its survival time is: Session ===> Once the browser is closed, the cookie will disappear ===> In the case of Cookie, if you send a request again, you will inevitably create a new one)

First of all, the client is no Cookie information, in the absence of Cookie's case, the client (browser) sends a request to the server (Tomcat), the server calls request.getSession () this API, create a session object, In the memory of the server (Session1, Session2, Session3...).

In the network request, the response:

Insert picture description here

He returns a cookie, the name of the cookie is called JSESSIONID, and its value is exactly the same as the id value of the cookie.

Session server every time you create a session, that they will create a Cookie object. The key of this Cookie object is always: JSESSIONID, and the value is the id value of the newly created Session.

At this time, in response to the newly created id value out of the Session returned to the client. Set-Cookie: JSESSIONID = 9055D85D3EB8F0922E3D5D56A8E776DE

Server analyzes the received data and immediately create a Cookie object.

After Cookie With behind every request of the Session id to the server in the form of a Cookie.

Call request.getSession () this API, the id value of the Cookie find the created Session object (to traverse memory), and returns.

Note: If you delete the Cookie in the Session, send a request to the server again , and then create a new Session object . Each time the server creates a Session object, it will create a Cookie object . The key of this Cookie object is always JSESSIONID , and the value is the value of the newly created Session .

The underlying technology insider icon:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45024585/article/details/112749147