[Java] How session works

1. The concept and characteristics of session

session concept

In computers, especially in web applications, it's called "session control." The Session object stores the properties and configuration information required for a specific user session. To put it bluntly, session is a data storage technology that can maintain the server side.

Sessions mainly have the following characteristics:

  1. The location where the session is saved is on the server side

  2. Generally speaking, sessions are used in conjunction with cookies. If the user's browser disables cookies, then URL rewriting can only be used to implement the session storage function.

  3. Simply use session to store user session information, then when there are many users, there will be a lot of session files, and there will be a problem of slow session query

Essentially: session technology is a temporary storage technology based on the backend that is different from the database.

2. Why use session

The Internet application layer protocols we currently use are basically based on HTTP and HTTPS, which are stateless and only responsible for requests and responses. I tell the server what I need, and the server returns me the corresponding resources. Without additional processing, the server does not know who you are, let alone show you content related to you based on who you are. There are some historical reasons why the HTTP protocol was originally designed like this. At that time, the Internet was mostly used for academic exchanges and was only used for things like the presentation of article information. It was far less colorful than it is now. Therefore, under the background of that time, the HTTP protocol was designed like this, which is actually very consistent with its scenario. However, as the Internet is becoming more and more widely used, there are more and more forms of applications. Our Web applications are not only limited to providing simple information display, but also require users to be able to log in, post in forums, and make purchases on shopping websites. Stuff etc. This requires the HTTP protocol to be able to record the user's status. That is the origin of the Session we are familiar with now.

3. Working principle of session

  1. When the user requests the server for the first time, the server will generate a sessionid
  2. The server returns the generated sessionid to the client through set-cookie
  3. When the client receives the sessionid, it will save it in a cookie. When the client visits the server again, it will bring this sessionid with it.
  4. When the server receives the request from the client again, it will first check whether the sessionid exists. If it does not exist, create a new sessionid and repeat the process of 1 and 2. If it exists, it will traverse the session file of the server and find the corresponding sessionid. file, the key value in the file is sessionid, and the value is some information about the current user
  5. Subsequent requests will exchange this Session ID for a stateful session.

4. Session life cycle

When does Session take effect?

Session is created when the user accesses the server for the first time. It should be noted that the Session will only be created when accessing JSP, Servlet and other programs. Only accessing static resources such as HTML and IMAGE will not create a Session. You can call request.getSession(true) to force Generate Session.

When does the session expire?

  1. The server will clear the Session that has been inactive for a long time from the server memory, and the Session will become invalid. The default expiration time of Session in Tomcat is 20 minutes. Calculated from the time when the session is inactive, if the session is always active, the session will never expire. The timing starts when the Session is not accessed; once the Session is accessed, the timing is cleared to 0;

  2. Call the invalidate method of Session

    HttpSession session = request.getSession();
    session.invalidate();//注销该request的所有session
    
  3. Set session expiration time

  • web.xml

    <session-config>
    <session-timeout>30</session-timeout>
    </session-config>
    
  • Set manually in the program

    session.setMaxInactiveInterval(30 * 60);//设置单位为秒,设置为-1永不过期
    
    request.getSession().setMaxInactiveInterval(-1);//永不过期
    
  • Tomcat can also modify the session expiration time. When defining context in server.xml, use the following definition:

    <Context path="/livsorder" 
    docBase="/home/httpd/html/livsorder"   defaultSessionTimeOut="3600" 
    isWARExpanded="true"   
    isWARValidated="false" isInvokerEnabled="true"   isWorkDirPersistent="false"/>
    
  • 4. Close the browser, the session will be invalid

5. Session performance bottleneck

Another thing we want to talk about is the storage of Session data. Normally, most web frameworks will store session data in memory if you don't set it explicitly. This is not a problem if your web application has a small number of users. But if your number of users is relatively large, one thing may happen - there is not enough memory. This is normal, and memory capacity is very valuable. Assuming that the session data of each user is 100K, 10,000 users will occupy about 1G of storage space. If your session data cleaning mechanism happens to be slow, the memory is very easy occupied. This requires you to consider the storage method of the Session when designing a site with a relatively large amount of concurrency, such as saving them to the hard disk file system or a database. So when you develop a Web application, if you have a large number of users, you need to be aware of this. In addition, there is another disadvantage of putting the Session in the memory. If your web server restarts, all Session states will be affected, which will affect the user experience to a certain extent.

6. Session controls login status

Assuming that the browser requests the server for the first time and needs to enter the user name and password to verify the identity, the server gets the user name and password and compares it to the database. Authorized" or "logged in" and so on, since it is the state of the session, it is naturally stored in the session object. Tomcat sets the login status in the session object as follows. When the user visits again, tomcat checks the login in the session object state.

Insert image description here

The login status in the session object is checked every time a protected resource is requested, and only sessions with isLogin=true can access it, so the login mechanism is implemented.

Guess you like

Origin blog.csdn.net/u011397981/article/details/132787404