Detailed explanation of the difference between cookie, session and localStorage

When you are browsing the website, the WEB server will first send a small piece of information on your computer, and the cookie will help you record the text or some choices you type on the website. When you visit the same website next time, the WEB server will first check if there is any cookie information left by it last time, and if there is, it will judge the user based on the content in the cookie, and send the specific webpage content to you. The use of cookies is very common. Many websites that provide personalized services use cookies to identify users, so as to facilitate the delivery of user-tailored content. For example, free email websites with web interfaces all use cookies.


Specifically, the cookie mechanism adopts the scheme of maintaining state on the client side, while the session mechanism adopts the scheme of maintaining state on the server side.

At the same time, we also see that since the server-side state-keeping scheme also needs to save an identity on the client side, the session mechanism may need to rely on the cookie mechanism to achieve the purpose of saving the identity, but in fact it has other options.

cookie mechanism. Orthodox cookie distribution is realized by extending the HTTP protocol. The server prompts the browser to generate the corresponding cookie according to the instruction by adding a line of special instructions in the HTTP response header. However, pure client-side scripts such as JavaScript or VBScript can also generate cookies. The use of cookies is automatically sent by the browser to the server in the background according to certain principles. The browser checks all stored cookies. If the scope declared by a cookie is greater than or equal to the location of the resource to be requested, the cookie is attached to the HTTP request header of the requested resource and sent to the server.
 
The content of the cookie mainly includes: name, value, expiration time, path and domain. The path, together with the domain, constitutes the scope of the cookie. If the expiration time is not set, it means that the lifetime of the cookie is during the browser session. When the browser window is closed, the cookie disappears. Such cookies that last for the browser session are called session cookies.

Session cookies are generally not stored on hard disk but in memory, although this behavior is not specified by the norm. If the expiration time is set, the browser will save the cookie to the hard disk. After closing and opening the browser again, these cookies are still valid until the set expiration time is exceeded. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different processing methods and session mechanisms. The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or possibly a hash table) to store information.

          When the 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 it does, it means that a session has been created for this client before. , the server retrieves this session for use according to the session id (if it cannot be retrieved, it will create a new one). If the client request does not contain a session id, a session will be created for this client and a session id associated with this session will be generated. , the value of session id should be a string that neither repeats nor easily finds patterns to imitate. This session id will be returned to the client in this response for preservation. The way to save this session id can use a cookie, so that the browser can automatically send this ID to the server according to the rules during the interaction process. Generally, the name of this cookie is similar to SEEESIONID. But cookies can be disabled artificially, and there must be other mechanisms to pass the session id back to the server when cookies are disabled.

A technique that is often used is called URL rewriting, which appends the session id directly to the URL path. There is also a technique called form hidden fields. That is, the server will automatically modify the form to add a hidden field so that the session id can be passed back to the server when the form is submitted. For example:
<form name="testform" action="/xxx"> 
< input type="hidden" name="jsessionid" value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764">
< input type="text"> 
</form> 
Actual The above technique can be simply replaced by applying URL rewriting to the action.

The difference between cookies and sessions:

1. The cookie data is stored on the client's browser, and the session data is stored on the server.

2. The cookie is not very safe. Others can analyze the cookie stored locally and perform cookie deception
   . Considering the security, the session should be used.

3. 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.
   In order to reduce the performance of the server, you should use cookies.

4. The data saved by a single cookie cannot exceed 4K. Many browsers limit a site to save a maximum of 20 cookies.

5. So personal suggestion:
   store important information such as login information as SESSION
   other information. If you need to keep it, you can put it in COOKIE

6. The session is stored on the server, and the client does not know the information; the cookie is stored on the client, and the server can know the information.   
    
  7. Objects are stored in session, and strings are stored in cookies.   
    
  8. Sessions cannot distinguish paths. During the same user's visit to a website, all sessions can be accessed anywhere. If the path parameter is set in the cookie, then the cookies under different paths in the same website cannot access each other.  
   

       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 the shopping cart in the online store? The 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 implemented by default using cookie. The system will create an output cookie named JSESSIONID, which we call session cookie to distinguish persistent cookies, which is what we usually call cookies. Note that session cookies are stored in browser memory, not written to the hard drive. 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 see it in the address bar. to a string like sessionid=KWJHUG6JJM65HS2K6.

 

    Specifically, the cookie mechanism adopts the scheme of maintaining state on the client side. It is a storage mechanism for session state on the client side, and he requires the user to enable client-side cookie support. The role of the cookie is an effort to solve the stateless defect of the HTTP protocol.
The session mechanism adopts a solution that maintains the state between the client and the server. At the same time, we also see that since the server-side state-keeping scheme also needs to save an identifier on the client side, the session mechanism may need to rely on the cookie mechanism to achieve the purpose of saving the identifier. The session provides a convenient way to manage global variables. The
session is for each user. The value of the variable is stored on the server. A sessionID is used to distinguish which user session variable is. This value is returned by the user's browser when accessing To the server, this value may also be set to be returned to the server by get when the client disables cookies.
    In terms of security: when you visit a site that uses session and create a cookie on your own machine, it is recommended that the SESSION mechanism on the server side is more secure. Because it will not arbitrarily read the information stored by the client.

    Orthodox cookie distribution is achieved by extending the HTTP protocol. The server prompts the browser to generate the corresponding cookie by adding a special line to the HTTP response header.
    From the web server's point of view, all HTTP requests are independent of previous requests. . That is to say, each HTTP response is completely dependent on the information contained in the corresponding request. The
    state management mechanism overcomes some of the limitations of HTTP and allows network clients and servers to maintain the relationship between requests. The period during which this relationship is maintained is called a session.
    Cookies are small pieces of text stored by the server on the local machine and sent to the same server with every request.

The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or possibly a hash table) to store information.

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

 

    When talking about the session mechanism, we often hear such a misunderstanding that "as long as the browser is closed, 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. 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, and the original session 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.

    Everyone knows that 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 context 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. cookie to achieve, the system will create an output cookie named JSESSIONID, we call it session cookie, to distinguish persistent cookies, which is what we usually call cookies, note that session cookies are stored in browser memory, not written to On the hard disk, 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 See a string like sessionid=KWJHUG6JJM65HS2K6 in the address bar.

 

Usually session cookies cannot be used across windows. When you open a new browser window and enter the same page, the system will give you a new sessionid, so the purpose of our information sharing cannot be achieved. The sessionid is saved in the persistent cookie, and then read out in the new window to get the SessionID of the previous window. In this way, through the combination of session cookie and persistent cookie, we can achieve cross-window session tracking.

The difference between web storage and cookies

The concept of Web Storage is similar to that of cookies, the difference is that it is designed for larger storage capacity. The size of the cookie is limited, and every time you request a new page, the cookie will be sent, which invisibly wastes bandwidth. In addition, the cookie needs to specify the scope and cannot be called across domains.

In addition, Web Storage has methods such as setItem, getItem, removeItem, clear, etc. Unlike cookies, front-end developers need to encapsulate setCookie and getCookie by themselves.

But cookies are also indispensable: the role of cookies is to interact with the server and exists as part of the HTTP specification, whereas Web Storage is only created to "store" data locally

 

 

sessionStorage, localStorage, and cookies are all data stored on the browser side. The concept of sessionStorage is very special, and a concept of "browser window" is introduced. SessionStorage is data that always exists in the same window (or tab) of the same origin. That is to say, as long as the browser window is not closed, even if the page is refreshed or another page of the same origin is entered, the data still exists. After closing the window, sessionStorage is destroyed. Different windows opened "independently" at the same time, even if it is the same page, the sessionStorage object is different.
 
Benefits of Web  Storage :
  1. Reduced network traffic: Once the data is stored locally, it is possible to avoid requesting data from the server, thus reducing unnecessary data requests and unnecessary transfers of data back and forth between the browser and the server.
  2. Display data quickly: good performance, reading data from local is much faster than getting data from server through network, local data can be obtained instantly. In addition, the webpage itself can also be cached, so if the entire page and data are locally, they can be displayed immediately.
  3. Temporary storage: In many cases, the data only needs to be used when the user browses a set of pages, and the data can be discarded after closing the window. In this case, it is very convenient to use sessionStorage.
 
 
Difference between browser local storage and server side storage
In fact, the data can be stored locally on the browser or on the server side.
 
The browser side can save some data, and get it directly from the local when needed, sessionStorage, localStorage and cookies are all data stored locally by the browser.
 
The server side can also save all the data of all users, but the browser needs to request data from the server when needed.
1. The server side can save the user's persistent data, such as databases and cloud storage, which save a large amount of user data on the server side.
2. The server side can also save the user's temporary session data. The server-side session mechanism, such as the JSP session object, the data is stored on the server. In terms of implementation, only the session id needs to be passed between the server and the browser, and the server finds the session object of the corresponding user according to the session id. Session data is only valid for a period of time, which is the session validity period set by the server.
 
The server-side saves all the user's data, so the server-side overhead is relatively large, while the browser-side saving distributes and saves the data required by different users in the users' respective browsers.
The browser side is generally only used to store small data, while the server can store large data or small data.
The server stores data safely, and the browser is only suitable for storing general data.
 
 
Difference between sessionStorage, localStorage and cookies
Common point: They are all saved on the browser side and are of the same origin.
the difference:
  1. Cookie data is always carried (even if not needed) in same-origin http requests, i.e. cookies are passed back and forth between browser and server. However, sessionStorage and localStorage do not automatically send data to the server, but only save it locally. The cookie data also has the concept of path (path), which can limit the cookie to belong to a certain path.
  2. The storage size limit is also different. The cookie data cannot exceed 4K. At the same time, because each http request will carry the cookie, the cookie is only suitable for storing small data, such as session ID. Although sessionStorage and localStorage also have storage size limits, they are much larger than cookies and can reach 5M or more.
  3. The validity period of data is different, sessionStorage: it is only valid until the current browser window is closed, and naturally it is impossible to keep it persistently; localStorage: it is always valid, and it is always saved when the window or browser is closed, so it is used as persistent data; cookie is only used in the set cookie Valid until the expiration time, even if the window or browser is closed.
  4. Different scopes, sessionStorage is not shared in different browser windows, even the same page; localStorage is shared in all windows of the same origin; cookies are also shared in all windows of the same origin.
  5. Web  Storage supports an event notification mechanism that can send notifications of data updates to listeners.
  6. The api interface of Web  Storage  is more convenient to use.

 
The difference between sessionStorage and page js data objects
The lifetime of the general js object or data in the page is only valid on the current page, so when the page is refreshed or the page is reloaded such as going to another page, the data does not exist.
In sessionStorage, as long as the same window (or tab) of the same origin, refresh the page or enter a different page of the same origin, the data will always exist. That is, as long as this browser window is not closed, a new page is loaded or reloaded, the data is still there.
 
http://blog.csdn.net/ljiechang/article/details/39004683

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326802695&siteId=291194637