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. Every 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.

         注意:在谈论session机制的时候,常常听到这样一种误解“只要关闭浏览器,session就消失了”。其实可以想象一下会员卡的例子,除非顾客主动对店家提出销卡,否则店家绝对不会轻易删除顾客的资料。对session来说也是一样的,除非程序通知服务器删除一个session,否则服务器会一直保留,程序一般都是在用户做log off的时候发个指令去删除session。然而浏览器从来不会主动在关闭之前通知服务器它将要关闭,因此服务器根本不会有机会知道浏览器已经关闭,之所以会有这种错觉,是大部分session机制都使用会话cookie来保存session id,而关闭浏览器后这个session id就消失了,再次连接服务器时也就无法找到原来的session。如果服务器设置的cookie被保存到硬盘上,或者使用某种手段改写浏览器发出的HTTP请求头,把原来的session id发送给服务器,则再次打开浏览器仍然能够找到原来的session。恰恰是由于关闭浏览器不会导致session被删除,迫使服务器为seesion设置了一个失效时间,当距离客户端上一次使用session的时间超过这个失效时间时,服务器就可以认为客户端已经停止了活动,才会把session删除以节省存储空间。大家都知道,http是无状态的协议,客户每次读取web页面时,服务器都打开新的会话,而且服务器也不会自动维护客户的上下文信息,那么要怎么才能实现网上商店中的购物车呢,session就是一种保存上下文信息的机制,它是针对每一个用户的,变量的值保存在服务器端,通过SessionID来区分不同的客户,session是以cookie或URL重写为基础的,默认使用cookie来实现,系统会创造一个名为JSESSIONID的输出cookie,我们叫做sessioncookie,以区别persistent cookies,也就是我们通常所说的cookie,注意sessioncookie是存储于浏览器内存中的,并不是写到硬盘上的,这也就是我们刚才看到的JSESSIONID,我们通常情是看不到JSESSIONID的,但是当我们把浏览器的cookie禁止后,web服务器会采用URL重写的方式传递Sessionid,我们就可以在地址栏看到sessionid=KWJHUG6JJM65HS2K6之类的字符串。

Guess you like

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