The difference between Cookie and Session

1, What is Cookie and Session?

We know that HTTP is a connectionless and stateless protocol, so the server cannot remember the status of this request every time the server is requested, resulting in each request being independent. In order for the web to generate some dynamic information, it is necessary to record status information, and cookies and sessions are generated to solve the stateless problem of the http protocol. Session tracking is a commonly used technique in web applications to track a user's entire session. Commonly used session tracking technologies are cookies and sessions. The cookie determines the identity of the user by recording information on the client. The session determines the identity of the user by recording information on the server.

Two session technologies   1) Browser-side session technology through cookie technology   2) Through Session technology, server-side session technology

2, cookie mechanism

When we buy things in Taobao, we usually put a lot of items in the shopping cart first, and then check out. But the web uses the stateless http protocol. If you don't track the user's information, then after you add the item to the shopping cart for the first time, the link is broken. When you add the shopping cart for the second time, you need to re-create it. Enter the account password to log in. Because at this time the server has been unable to judge whether the behavior of joining the shopping cart is still the original user. A cookie is a mechanism that tracks the role of a session in a scenario like this.

cookie is actually a short piece of text information. The client requests the server. If the server needs to record the user status, it uses response to issue a cookie to the client browser. The client browser saves the cookie. When the browser requests access to the website again, the browser requests the request. The website is submitted to the server along with the cookie, which checks the cookie to identify the user's status.

写写图片 description


In short, the working principle of cookies can be summarized as follows: 1) When the browser was first accessed by the browser, there was no cookie. 2) The cookie is created by the server and sent to the browser via the response header Set-Cookie. 3) The browser receives the cookie information sent by the server and stores it on the local hard disk. 4) Send the locally saved cookie information to the server the next time you access the server. 5) The server can receive the cookie information again, read and operate

3, Session mechanism

When the program needs to create a session for a client request, the server will check whether the client's request is checked. Has included a session identifier (session id), if it is included, the server has previously created a session for this client, the server will retrieve its session according to the session id (retrieve will create a new One).

If the client request does not contain the session id, the server will create a new session for the client and generate the session id associated with the session. The session id will be returned to the client for saving in this response. The method can use cookies.

The principle analysis of the session:


In simple terms, the session mechanism can be summarized as follows: 1) The first access server has no session, call getSession() to create a session, and assign a session ID. 2) The server sends the session ID to the browser as a cookie. The name of the cookie is JSESSIONID. 3) The browser gets the session ID, and the session ID is sent to the server as a cookie the next time it is accessed. 4) The server gets the session ID to distinguish between different clients.

Session Technology features:    1) Server-side session technology, data is stored in the server's memory.     2) One user per session     3) Data cannot be shared between sessions and sessions

A technique that is often used is called URL rewriting, which simply attaches 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 and add a hidden field to pass the session id back to the server when the form is submitted. Both cookies and Sessions are capable of session tracking, but the principles are not the same. Under normal circumstances, both can meet the needs, but sometimes they can not use cookies, and sometimes can not use Session. The following is a comparison of the characteristics of the two and the applicable places.

4. The difference between cookie and session

4.1 The access method (data structure) is different

1) The data type key and value in the cookie must be a string type   2) The Session key is a string type, the value is of type Object, and any type is stored.

Cookie can only store ASCII strings. If you need to access Unicode characters or binary data, you need to encode them first. Java objects cannot be accessed directly in cookies. To store slightly more complex information, using cookies is harder.

The Session can access any type of data, including but not limited to String, Integer, List, Map, and so on. Session can also directly store Java Beans and even any Java classes, objects, etc., which is very convenient to use. Think of Session as a Java container class.

4.2 Different privacy policies

1) Cookie data is stored on the client, visible, easy to leak   2) Session data is saved on the server side and has high security.

Cookies are stored in the client reader and are visible to the client. Some programs on the client may snoop, copy, and modify the contents of the cookie. The Session is stored on the server and is invisible to the client. There is no risk of sensitive information being leaked.

If you choose a cookie, the better way is to try not to write sensitive information such as account password.

It is best to encrypt the cookie information like Google and Baidu, and then decrypt it after submitting it to the server to ensure that the information in the cookie can be read by myself. If you choose Session, it saves a lot of trouble. Anyway, it is placed on the server, and any privacy in the Session can be effectively protected.

4.3 Different server pressures

1) Session is kept on the server side, each user will generate a session, and the pressure is high.   2) The cookie is kept on the client, and the server resource is not occupied.

Session is stored on the server side. Each user will generate a session, and the pressure will be high. If there are a lot of concurrent users, it will generate a lot of Session and consume a lot of memory. Therefore, websites with high concurrent traffic such as Google, Baidu, and Sina are unlikely to use Session to track customer sessions.

Cookie is kept on the client and does not occupy server resources. If there are so many users reading concurrently, cookies are a good choice. For Google, Baidu, and Sina, cookies may be the only choice.

4.4 Different on the expiration date

1) Expiration of the cookie: By default, the browser closes the cookie and expires   2) Session default is 30 minutes

Cookie Object method 说明
void setMaxAge(int expiry) Set the expiration time in seconds
Set to positive: in seconds
设置0: Delete Cookie
is set to a negative number: the browser closes expires

Session Object method session.setMaxInactiveInterval(s)Set session maximum inactivity interval

Anyone who has used Google knows that if you have logged in to Google, Google’s login information will be valid for a long time. Users don't have to log in again every time they visit, Google will permanently record the user's login information. To achieve this effect, using cookies would be a good choice. Just set the cookie's expiration time attribute to a very large number.

Since the Session relies on a cookie named JSESSIONID, and the expiration time of the Cookie JSESSIONID defaults to –1, the Session will be invalidated by simply closing the reader, so the Session cannot complete the information forever.

Rewriting with URL address can't be done. Moreover, if the timeout period for setting the Session is too long, the more Sessions the server will accumulate, the more likely it is to cause memory overflow.

问: If the browser is closed, does the session information on the server still exist?   A: The information on the server still exists, and the session domain also has expired time. It will not disappear until the session expires.

问: Why can't I get the information in the previous session domain again after the browser is closed?   Because the cookie expires after the browser is closed, the JSESSIONID is gone, and the next time you get another session ID, you can't get the data from the previous session domain.

4.5 Different on cross-domain support

1) Cookies can be accessed across second-level domains   2) Session does not support cross-domain access

Cookie can be accessed across the second-level domain name, this is a good understanding, for example, you created a cookie in the web application where is located, at Such a second-level domain name can be accessed in the application, of course, you need to point out that the Domain property is when creating the cookie.

cross-domain cookies are now commonly used on the web, such as Google, Baidu, Sina, etc.

Session does not support cross-domain access. Session is only valid within the domain name in which he is located.


Using only cookies or using Session alone may not achieve the desired results. At this time, you should try to use both cookies and sessions. The combination of cookies and Sessions will accomplish a lot of unexpected results in the practice project.