[Java Web] The Road to Learning Session and Cookie


1. Background

Session (Session) is used to track the user's entire session. Commonly used session tracking technologies are: Session and Cookie. Cookie confirms the user's identity by recording information on the client side, and Session confirms the user's identity by recording information on the server side.

Because the HTTP protocol is a connectionless protocol, that is, when a client sends a request to the server, the server receives the request, and returns a response, the connection ends, and the server does not save relevant information. To make up for this shortcoming, the HTTP protocol provides session and cookie.

Second, deep understanding of Session and Cookie

1. Understand Session

Understanding the session object:
Definition : A session is a text file stored on the server and retains various tracking information of the user.
Role : Session retention, such as completing the user's login and status retention, is relatively safer because it is on the server side.

HttpSession object

  1. Servlet also provides the HttpSession interface, which provides a way to identify users and store information about users when requesting across multiple pages or visiting a website.
  2. The Servlet container uses this interface to create a session between the HTTP client and the HTTP server. The session lasts for a specified period of time and spans multiple connections or page requests.
  3. We can get the HttpSession object by calling the public method getSession() of HttpServletRequest, as shown below:
    Insert picture description here

The Session object is called a session. Through the session, you can save the user's state when jumping between the web pages of the application, so that the entire session will exist until the browser is closed. However, if the client does not send a request to the server for a long time in a session, The session object will disappear. The length of this time depends on the server, for example: Tomcat server default time is 30 minutes. But this time can be modified by writing a program.

In fact, the process of a conversation can also be understood as a process of making a call. The call starts from picking up the phone or dialing on the mobile phone and ending when you hang up. During this process, you can chat with the other party on many topics, even repetitive topics. The same is true for a session, you can visit the same Web page repeatedly.

When is the session created?
A common misunderstanding is that people think that the session is created when the client accesses it, but in fact it is not until a server-side program calls HttpServletRequest. The statement like getSession(true) will be created.

When is the session deleted?
(1) The program calls HttpSession.invalidate();
(2) The time since the last session id sent by the client was received exceeds the maximum valid time of the session;
(3) The server process is stopped.
It should be noted that closing the browser will only invalidate the session cookie stored in the client browser, and will not invalidate the session object on the server side, unless the session on the server side has just reached the expiration time.

2. Understand Cookies

Definition: Cookies are text files stored on the client computer and retain various tracking information of the user;
Function: Session retention, such as completing the user's login and status retention;

How cookies work:

  • The client initiates a login request to the service area, and the server script sends a set of Cookies to the browser. For example: name, age or identification number, etc.
  • The browser stores this information on the local computer for future use.
  • The next time the browser sends any request to the Web server, the browser will send these Cookies information to the server, and the server will use the information to identify the user.

Cookie composition:
Cookies are usually set in HTTP header information. The HTTP request to set the Cookie will send the following header information to the Servlet:
Insert picture description here

  • The Set-Cookie header contains a name-value pair, a GMT date, a path, and a domain. The name and value will be URL encoded.
  • The expires field is an instruction that tells the browser to expire ("forget") the cookie after a given time and date.
  • If the browser is configured to store cookies, it will retain this information until the expiration date.

Servlet operation cookie method:
get a static webpage, submit:
Insert picture description here

Three, Session's workflow

Functional application scenarios are similar to cookies, which are used to store a small amount of data or information.
work process:

  1. When the client sends a request to the server, it checks to see if there is a cookie file locally. If so, it contains a line of cookie information in the HTTP request header (Request Headers);
  2. When the server receives the request, it obtains the session id according to the cookie information,
    finds the corresponding session according to the session id, and uses this session to determine whether the user is logged in, etc.

Fourth, the application scenario of Cookie

Usage scenario: Ten days free login operation

Realization: Save the user's information locally on the client (under the local path related to the browser, save the user information to a local file), which is equivalent to saving a file on the local client, and the server can respond to the browser's set -Cookie header, get cookie information. When a user registers on a certain website, he will receive a cookie with a unique user ID. When the client reconnects later, the user ID will be automatically returned, and the server will check him to determine whether it is a registered user and select automatic Log in, so that the user needs to give a user name and password to access the server's resources . And you can set a deadline for this file yourself, this period of time will not disappear because the browser is closed. This effect is reflected in many shopping websites. The website can use cookies to remember the user's wishes. For simple settings**, the website can directly set the page in the cookie to complete the customization. For the more complex, the website only needs to send a unique identifier to the user, and the server-side database stores the page settings corresponding to each identifier. **In this way, the website can remember your preferences through the products you browse, and recommend things you like. The business is really taking so hard! ! !

Five, the difference between Session and Cookie

The difference between Session and Cookie:
1. The cookie data is stored on the client's browser, and the session data is stored on the server.

2. The session will be saved on the server for a certain period of time. When the number of visits increases, it will take up the performance of your server. When considering reducing server performance, cookies should be used.

3. The two biggest differences are: the difference in life cycle. One is IE starts to IE closes. (The session disappears as soon as the browser is closed), one is a preset life cycle, or a file (cookie) that is permanently stored locally.

Six, the life cycle of Session and Cookie

Session life cycle:
When a user accesses the server for the first time and is created, as long as the user continues to access, the server will update the last access time of the session. When more and more users access the server, there will be more and more sessions, but in order to prevent memory overflow, the server will delete the sessions that have not been active for a long time from the memory. This time is the timeout of the session. time. If the server has not been accessed for more than the timeout period, the session will automatically become invalid.

Cookies also have long-term and short-term distinctions : the cookie life cycle can be set by cookie.setMaxAge(2000);, if setMaxAge is not set, the cookie life cycle will disappear when the browser is closed.

In the same period of time, the life cycle of the cookie is cumulative, while the life cycle of the session is interval. As long as the user keeps accessing the session, the lifetime of the session will be continuously recalculated.

Summary:
When the user closes the browser, only the session and cookie in the browser memory disappear, but the session object saved on the server side will not disappear, nor will the persistent cookie saved on the hard disk disappear.

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/114380334