Detailed HttpSession (referred to as session)

session overview

  • Session represents a session, not only exists in javaweb, as long as it is web development, there is a session mechanism.
  • The corresponding type of session in java is: javax.servlet.http.HttpSession, referred to as session/session
  • In java web, session is a java object stored on the WEB server, which represents a session between the user and the WEB server.

So what is a conversation?

  • In most cases, it is described as follows: the user opens the browser, performs some operations on the browser, and then closes the browser, which means that a session is over.
  • Essential description: from the creation of the session object to the destruction of the final session object after the timeout, this is a complete session in the true sense.
  • Cookie can save the session state on the browser client side, and HttpSession can save the session state on the WEB server side.
  • During the session, the web server maintains a session object/HttpSession for the current user
  • In the WEB container, the WEB container maintains a large number of HttpSession objects. In other words, there should be a "session list" in the WEB container
    • That is to say, when Zhang San visits the WEB server, the server will generate a session object of Zhang San, and when Li Si visits the WEB server, the server will generate a session object of Li Si.
    • The system sets up an independent session object for each visitor to access data, and the session objects of each visitor do not interfere with each other.
  • Session and cookie are closely related
    • Cookie can save the session state on the client side, and HttpSession can save the session state on the server side.
    • The use of session requires that the user's browser must support cookies. If the browser does not support the use of cookies, or is set to disable cookies, the session cannot be used.

Thinking about the following questions? ? ?

Suppose there are two users, one is Zhang San from Beijing and the other is Li Si from Nanjing, both visiting the JD Mall shopping website, then there must be two shopping carts in the JD WEB server, one is Zhang San’s shopping cart, One is the shopping cart belonging to Li Si. Everyone is thinking: a WEB server and two browser clients, why Zhang San must put the goods in the shopping cart into Zhang San’s shopping cart when shopping. It will not be stored in Li Si’s shopping cart, that is to say, how is the session bound to a specific user?

  • The following uses graphics to describe the working principle of session:
    Insert picture description here

The working principle of session:

 1. 打开浏览器,在浏览器上发送首次请求
 2. 服务器会创建一个HttpSession对象,该对象代表一次会话
 3. 同时生成HttpSession对象对应的Cookie对象,并且Cookie对象的name是jsessionid,Cookie的value是32位长度的字符串(jsessionid=xxxx)
 4. 服务器将Cookie的value和HttpSession对象绑定到session列表中
 5. 服务器将Cookie完整发送给浏览器客户端
 6. 浏览器客户端将Cookie保存到缓存中
 7. 只要浏览器不关闭,Cookie就不会消失
 8. 当再次发送请求的时候,会自动提交缓存中当的Cookie
 9. 服务器接收到Cookie,验证该Cookie的name是否是jsessionid,然后获取该Cookie的value
 10. 通过Cookie的value去session列表中检索对应的HttpSession对象 
  • To be careful of
  • When the browser is closed, the cookie in the cache disappears, so that the client cannot get the server-side session object when it visits the server next time. This means that the session has ended, but it does not mean that the session object on the server side is immediately recycled. The session object is still stored in the session list. When no user accesses the session object for a long time, we call it session timeout. At this time, the web server The session object will be recycled.

1. After the browser is closed, will the session object corresponding to the server be destroyed?

  • After the browser is closed, the server will not destroy the session object
  • Because the B/S architecture system is based on the HTTP protocol, and the HTTP protocol is aNo connection/statelessAgreement
  • So what is connectionless/stateless?
    • The channel between the browser and the server is opened at the moment of the request. After the request response is completed, the channel is closed
    • The purpose of this is to reduce the pressure on the server

2. When is the session object destroyed?

  • When no user accesses the session object for a long period of time (this time can be configured), and the session object times out, the web server will automatically recycle the session object
  • This timeout period can be configured, in the web.xml file, the default is 30 minutes
    <session-config> <session-timeout>120</session-timeout> </session-config>

3. Under what circumstances is a session ended?
1. The browser is closed, the cookie in the cache disappears, the session may not end, because the server-side session object has not been destroyed. At this time, we can inherit the session object through the URL rewriting mechanism.
2. The browser is not closed, but because the web server has not been accessed for a long time, the server determines that the session has timed out and destroys the session object. Although the browser is not closed at this time, the session has ended.
3. The name of the Cookie associated with the session object is a bit special, the name must bejsessionidAll lowercase, at this time the HTTP protocol stipulates.
4. The browser has disabled cookies, and you can use the URL rewriting mechanism (the cost of encoding is relatively high, so generally websites are not allowed to disable cookies)
5. How to rewrite the URL: http://ip:port/webapp/ servlet/accessSys;jsessionid=xxxxxx

About commonly used methods in javax.servlet.http.HttpSession interface:

  • Get the session object, create a new one if not
request.getSession(true); request.getSession();
  • Get the session object, if it cannot be obtained, return null
request.getSession(false);
  • Store a piece of data in the session
void setAttribute(String name, Object value);
  • Retrieve data from the session range
Object getAttribute(String name);
  • Delete data from the session scope
void removeAttribute(String name);
  • Destroy session
void invalidate();

These methods can be applied through the following demo cases

  • Step 1 : Create a welcome pagelogin.html, The path of the first hyperlink in it points to the class that stores a data in the session scope, the path of the second hyperlink points to the class that retrieves data from the session scope, and the path of the third hyperlink points to the destruction of the session object the type.
<body>
    <a href="/hcz21/user/accessMySelfSessionServlet">访问属于我的会话对象</a>
    <br>
    <a href="/hcz21/user/getDataFromSession">从会话对象取出数据</a>
    <br>
    <a href="/hcz21/logout">安全退出</a>
</body>
  • Step two : inweb.xmlConfigure the path specified in the first step hyperlink in the file
<welcome-file-list>
    <welcome-file>login.html</welcome-file>
</welcome-file-list>

<servlet>
    <servlet-name>accessMySelfSessionServlet</servlet-name>
    <servlet-class>com.javaweb.servlet.AccessMySelfSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>accessMySelfSessionServlet</servlet-name>
    <url-pattern>/user/accessMySelfSessionServlet</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>getDataFromSession</servlet-name>
    <servlet-class>com.javaweb.servlet.GetDataFromSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>getDataFromSession</servlet-name>
    <url-pattern>/user/getDataFromSession</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>logout</servlet-name>
    <servlet-class>com.javaweb.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>logout</servlet-name>
    <url-pattern>/logout</url-pattern>
</servlet-mapping>
  • Step 3 : CreateAccessMySelfSessionServlet.javaClass, inherit the HttpServlet interface and rewrite the doGet method, obtain the current session object through request, and then store a data in the session scope
public class AccessMySelfSessionServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        String ip = request.getRemoteAddr();
        HttpSession session = request.getSession();
        System.out.println(ip+"'s session ="+session);

        //向session中存储一个数据
        session.setAttribute("username","张三");
    }
}
  • Step 4 : CreateGetDataFromSessionServlet.javaClass, inherit the HttpServlet interface and rewrite the doGet method, get the current session object through request, and then retrieve the data from the session scope
public class GetDataFromSessionServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        HttpSession session = request.getSession();
        //从session范围中取出数据
        Object username = session.getAttribute("username");
        System.out.println(username);
    }
}
  • Step 5 : CreateLogoutServlet.javaClass, inherit the HttpServlet interface and rewrite the doGet method, obtain the current session object through request, and then destroy the session object
public class LogoutServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取session对象,若没有获取到session对象则创建一个session对象、
        //HttpSession session = request.getSession();

        //获取session对象,若没有获取到session对象则创建一个session对象、
        //HttpSession session = request.getSession(true);

        //获取session对象,若没有获取到session对象则返回null
        HttpSession session = request.getSession(false);
        if (session!=null){
    
    
            //销毁session对象
            session.invalidate();
        }
    }
}
  • Step 6 : When clickingVisit my session objectThis hyperlink will store the data "username=Zhang San" in the server; when you click againGet data from the session objectWith this hyperlink, the data "username=Zhang San" can be taken out, and the running result is as follows:
    Running result graph
  • Step 7 : When clickingRetreat safelyThis hyperlink, then the server will destroy the user’s session; when you click againGet data from the session objectWhen this hyperlink is used, the data retrieved is empty, and the result of the operation is as follows:
    Running result graph

Comparison of ServletContext, HttpSession, and HttpServletRequest interfaces:

  • 1. The above are all scope objects:
    • ServletContext application; is the scope of application
    • HttpSession session; is the session scope
    • HttpServletRequest request; is the request scope
  • 2. The sorting of the three ranges:
    • application > session > request

Similarities : Both can be used to transfer data, and they all have the same data access method

  • 存:session.setAttribute(“name”,ObjectValue);
  • 取:Object value = session.getAttribute(“name”);
  • 删: session.removeAttribute(“name”);

Difference :

  • ServletContext (application) is a Servlet context object. The web.xml file is parsed to create a ServletContext object during the server startup phase. All Servlet objects in the same webabb share the same ServletContext object. Once created, the object will not be destroyed unless the server is stopped. i. So try not to store big data in this object, because this is a space shared by all users. If the data stored in this object involves modification operations in a multi-threaded environment, pay attention to thread safety issues. The data generally stored in the object is firstA small amount of data shared by all users, will not be modified. The ServletContext object can pass data across Servlet, across requests, and across users (cross-session) .
  • HttpSession (session) is a session object. Every user has such an object. The data stored in this object is generally the user-specific data. For example, the shopping cart object can be stored in the session, and the HttpSession object can pass data across Servlet, cross-request (these requests must belong to the same session), but cannot pass data across users .
  • HttpServletRequest (request) is a request object, one object at a time, and a new request object is created for each request. It is a request-level object. The data stored in the object is generally request-level data. After a request, this data is not Re-used data can be stored in this object. The HttpServletRequest object can pass data across servlets, but it cannot pass requests, let alone pass data across users .
  • 3. Principles of use:From small to largeTry, give priority to using a small range (consideration principle: request <session <application)
    • For example: after a successful login, the logged-in state needs to be saved, and the successful login state can be saved to the session object. The login success status cannot be saved in the request scope, because a request corresponds to a new request object. The login success status cannot be saved to the application scope, because the login success status belongs to the session level and cannot be shared by all users.

Guess you like

Origin blog.csdn.net/hcz666/article/details/108916119