Web Classic Problems - Session and Cookies

         As we all know, session tracking is a commonly used technology in Web programs to track the user's entire session. Commonly used session tracking technologies are cookies and sessions. The cookie determines the user's identity by recording information on the client side (the session is stored on the server side), and the session determines the user identity by recording the information on the server side. The cookie is stored on the client side (the cookie is stored on the client side). Sessions may depend on cookies, but let's be more specific, would you? I am often dizzy by this question, and I have found a lot of information on the Internet, which is specially organized and summarized here for friends in need to view.

        cookie mechanism

       In programs, session tracking is a very important thing. In theory, all request operations of one For example, any product purchased by user A in the supermarket should be placed in A's shopping cart. No matter when user A purchased it, it belongs to the same session and cannot be placed in user B's or user C's shopping cart. , which do not belong to the same session. Web applications, on the other hand, use the HTTP protocol to transfer data. The HTTP protocol is a stateless protocol. Once the data exchange is completed, the connection between the client and the server is closed, and a new connection needs to be established to exchange data again. This means that the server cannot track the session from the connection. That is, when user A buys a product and puts it into the shopping cart, the server cannot determine whether the purchase belongs to the session of user A or the session of user B when the product is purchased again. To keep track of this session, a mechanism must be introduced. Cookie is such a mechanism (that is, to issue a pass to the client, one for each person, no matter who visits must carry their own pass. This way the server can confirm the identity of the client from the pass. This is how Cookie works .) . It can make up for the lack of statelessness of the HTTP protocol. Before the advent of Session, basically all websites used cookies to track sessions.

     Cookie Features and Functions

      Cookies are not cross-domain . According to the cookie specification, browsers accessing Google will only carry Google's cookie, but not Baidu's cookie. Google can only operate Google's cookies, but not Baidu's cookies. Cookie realizes the single sign-on function : query the database once when logging in, and no longer query the database when accessing and verifying the login information in the future. The implementation method is to encrypt the account and password according to certain rules, and save them together with the account in a cookie. The next time you visit, you only need to determine whether the cookie value of the corresponding user has changed or expired. In this example, the account number, password, and request address are spliced ​​into a string, encrypted with md5, and saved in a cookie named xxx.xxx.account. When the same account is verified, the cookie value generated by the login and the cookie value stored in the browser are verified . If they are equal, if they are equal, the user will directly log in and jump to the home page (without the login judgment logic), otherwise the login logic will be executed, and the generated cookie value will be stored according to the specified rules.

      Session mechanism:

       Session is another mechanism for recording client state, the difference is that cookies are stored in the client browser, while sessions are stored on the server. When the client browser accesses the server, the server records the client information on the server in some form. This is Session. When the client browser accesses again, it only needs to look up the status of the client from the Session. If the Cookie mechanism is to determine the client's identity by checking the "passport" on the client, then the Session mechanism is to confirm the client's identity by checking the "client list" on the server. Session is equivalent to a client profile created by the program on the server. When a client visits, they only need to query the client profile table.

      Session Features and Functions

      The Session object is created when the client first requests the server. When multiple clients execute the program, the server will save the sessions of multiple clients. When acquiring a Session, you do not need to declare whose Session is to be acquired. The Session mechanism determines that the current client can only get its own Session, but not other people's Sessions. The sessions of each client are also independent of each other and invisible to each other. The use of sessions is more convenient than cookies, but too many sessions are stored in the server memory, which will put pressure on the server.

       Session is stored on the server side. In order to obtain higher access speed, the server generally puts the Session in memory. Each user will have an independent Session. If the Session content is too complex, it may cause memory overflow when a large number of clients access the server. Therefore, the information in the Session should be as concise as possible. Sessions are automatically created when a user accesses the server for the first time. It should be noted that a Session will only be created when accessing programs such as JSP and Servlet, and only accessing static resources such as HTML and IMAGE will not create a Session. If the Session has not been generated, you can also use request.getSession(true) to force the Session to be generated. After the session is generated, as long as the user continues to access, the server will update the last access time of the session and maintain the session. Each time a user accesses the server, regardless of whether the session is read or written, the server considers the user's session to be "active" once. As more and more users access the server, there will be more and more sessions. To prevent memory overflow, the server will delete sessions that have not been active for a long time from memory. This time is the Session timeout. If the server has not been accessed after the timeout period, the session will be automatically invalidated. Although the session is stored on the server and is transparent to the client, its normal operation still requires the support of the client browser. This is because Session needs to use cookies as identification signs. The HTTP protocol is stateless, and the Session cannot determine whether it is the same client based on the HTTP connection, so the server sends a cookie named JSESSIONID to the client browser, whose value is the id of the Session (that is, HttpSession. return value of getId()). Session identifies whether it is the same user based on this cookie. This cookie is automatically generated by the server, and its maxAge attribute is generally -1, which means that it is only valid in the current browser, and is not shared between browser windows, and it will be invalid when the browser is closed. Therefore, when two browser windows of the same machine access the server, two different sessions will be generated. The exception is new windows opened by links, scripts, etc. within the browser window (that is, windows that are not opened by double-clicking a desktop browser icon, etc.). Such child windows will share the cookie of the parent window, so they will share a Session. Note: Newly opened browser windows will generate new sessions, except for child windows. The child window will share the Session of the parent window. For example, when you right-click on the link and select "Open in New Window" from the pop-up shortcut menu, the child window can access the session of the parent window. What if the client browser disables the cookie function, or does not support cookies? For example, the vast majority of mobile browsers do not support cookies. Java The Web offers another solution: URL address rewriting. TOMCAT determines whether the client browser supports cookies based on whether the request contains cookies. Although the client may support cookies, since the first request will not carry any cookie (because there is no cookie to carry), the rewritten URL will still contain jsessionid. When accessing for the second time, the server has already written a cookie in the browser, so the rewritten URL will not have jsessionid in it. When a program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier - called session id. If a session id is included, it means that this client has been previously Once a session has been created, the server retrieves the session for use according to the session id (if it cannot be retrieved, it may create a new one). If the client request does not contain the session id, it creates a session for the client and generates a session related to this session. The associated session id, the value of the session id should be a string that is neither repeated nor easy to find patterns to imitate. This session id will be returned to the client in this response for preservation.

        Note: When talking about the session mechanism, one often hears the misunderstanding that "as long as you close the browser, the session disappears". In fact, you can imagine the example of a membership card. Unless the customer takes the initiative to cancel the card, the store will never delete the customer's information easily. The same is true for sessions. Unless the program notifies the server to delete a session, the server will keep it all the time. The program generally  sends an instruction to delete the session when the user logs off. However, the browser never actively informs the server that it will be closed before closing, so the server has no chance to know that the browser has been closed. The reason for this illusion is that most session mechanisms use session cookies to save session  id. , and the session id disappears after closing the browser, and the  original session cannot be found when connecting to the server again. If the cookie set by the server is saved to the hard disk, or some method is used to rewrite the HTTP request header sent by the browser, the original session If the id is sent to the server, the original session can still be found by opening the browser again. It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the session. When the time since the client last used the session exceeds this expiration time, the server can consider that the client has stopped activities. The session will be deleted to save storage space. As we all know, http is a stateless protocol. Every time a client reads a web page, the server opens a new session, and the server does not automatically maintain the client's context information, so how can we implement a shopping cart in an online store? Well, session is a mechanism for saving contextual information. It is for each user. The value of the variable is stored on the server side, and different customers are distinguished by SessionID. Session is based on cookie or URL rewriting, and is used by default. To achieve this, the system will create an output cookie named JSESSIONID, which we call sessioncookie to distinguish persistent cookies, which is what we usually call cookies. Note that sessioncookies are stored in browser memory, not written to the hard disk. Yes, this is the JSESSIONID we just saw. We usually can't see the JSESSIONID, but when we disable the browser's cookie, the web server will use URL rewriting to pass the Sessionid, and we can use the URL to rewrite the Sessionid. column to see a string like sessionid=KWJHUG6JJM65HS2K6.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325764512&siteId=291194637