The difference between cookie and session: the session lifecycle,

Source: Internet
Author: User

These are basic knowledge, but it is necessary to have a deep understanding. First, let's give a brief introduction.

Definitions:

When you are browsing the website, the web server will first send a small piece of information to your computer, and the cookie will help you with the text or some choices on the website,

All records are recorded. When you visit the same website next time, the web server will first check whether there is any cookie information left by the Web server.

To determine the user and send specific webpage content to you. Cookies are widely used. Many websites that provide personalized services use cookies.

To identify users and send out customized content, such as a free email website using web interfaces, cookie is required.


Specifically, the cookie mechanism adopts the client-side persistence scheme, while the session mechanism adopts the server-side persistence scheme.

At the same time, we also see that because the server-side persistence scheme also needs to save an identifier on the client, the session mechanism may need to rely on the cookie mechanism.

To save the identity, but in fact it has other options.

COOKIE Mechanism. The orthodox cookie distribution is implemented by extending the HTTP protocol, and the server adds a special line of instructions to the HTTP response header to prompt

The browser generates the corresponding cookie as instructed. However, pure client scripts such as JavaScript or VBScript can also generate cookies. Cookie usage

It is automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. If a cookie is declared to be effective

If the value 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.
 
Cookie content mainly includes: name, value, expiration time, path and domain. The path and the domain form the scope of the cookie. If the expiration time is not set,

The life cycle of each cookie is the browser session. When the browser window is closed, the cookie disappears. This cookie is called a session cookie.

Session cookies are generally stored in the memory instead of on the hard disk. Of course, this behavior is not standardized. If the expiration time is set, the browser will set the cookie

Save it to the hard disk, close it, and open the browser again. These cookies are still valid until the specified expiration time is exceeded. Cookies stored on hard disks can be stored in different regions.

The process of the browser is shared, such as two IE Windows. For Cookies stored in the memory, different browsers have different processing methods.

Session mechanism. The session mechanism is a server-side mechanism. The server uses a structure similar to a hash (or a hash) to save information.

When the program needs to create a session for a client request, the server first checks whether the client request contains a session ID.

(Called session ID). if it already exists, it indicates that a session has been created for this client before, and the server retrieves the session according to the session ID.

If the client request does not contain the session ID, a session is created for the client and

The associated session ID. The value of the session ID should be a string that is neither duplicated nor easily found to be counterfeited. This session ID will be returned in this response.

. The cookie can be used to save the session ID. In this way, the browser can automatically send the ID

Server. Generally, the cookie name is similar to seeesionid. However, if a cookie can be artificially disabled, other mechanisms must be in place to prevent the cookie from being disabled.

The session ID can still be passed back to the server.

A frequently used technology called URL rewriting is to directly append the session ID to the end of the URL path. Another technique is form hidden fields. Is the server

The form is automatically modified and a hidden field is added 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>
In fact, this technology can be simply replaced by rewriting the URL of the action application.

Differences between cookie and Session:

1. Cookie data is stored in the client's browser, and session data is stored on the server.

2. Cookies are not safe. Others can analyze the Cookies stored locally and perform cookie spoofing.
Session should be used for security consideration.

3. The session will be stored on the server for a certain period of time. When the number of accesses increases, it will occupy the performance of your server.
Cookie should be used in consideration of reducing server performance.

4. data stored in a single cookie cannot exceed 4 kb. Many browsers limit that a site can store up to 20 cookies.

5. Personal suggestions:
Store important information such as login information as session
Other information can be stored in the cookie if it needs to be retained.

 

 

Ii. Session Lifecycle

The session is stored on the server. Generally, to prevent the session from being stored in the server's memory (for high-speed access), sessinon is created when the user accesses the server for the first time, you must note that the session will be created only when you access JSP, Servlet, and other programs. The session will not be created only when you access static resources such as HTML and image. You can call the request. getsession (true) Forcibly generates a session.

  When does the session expire?

1. The server clears sessions that have not been active for a long time from the server memory, and the session becomes invalid. The default expiration time of session in Tomcat is 20 minutes.

2. Call the invalidate method of the session.

  Session requirements for browsers:

 Although the session is stored on the server and transparent to the client, its normal operation still requires support from the client browser. This is because the session needs to use cookies as the identification mark. The HTTP protocol is stateless, and the session cannot determine whether it is the same customer based on the HTTP connection. Therefore, the server sends a cookie named JSESSIONID to the client browser, the value is the session ID (httpsession. return Value of GETID ). The session identifies whether the session is the same user based on the cookie.

 

The cookie is automatically generated by the server. Its maxage attribute is generally-1, indicating that the cookie is valid only in the current browser and is not shared among various browser windows. If you close the browser, it will become invalid. Therefore, when two browser windows of the same machine access the server, two different sessions are generated. Except for new windows opened by links and scripts in the browser window (that is, windows opened by double-clicking the desktop browser icon. This type of child window will share the cookie of the parent window, so it will share a session.

 

Note: New sessions are generated in the new browser window, except for subwindows. The Child Window shares the session of the parent window. For example, if you right-click the link and select "open in New window" in the shortcut menu, the Child Window can access the session in the parent window.

 

What if the client browser disables or does not support cookies? For example, most mobile Browsers Do not support cookies. Java Web provides another solution: URL address rewriting.

URL address rewriting is a solution that does not support cookies on the client. The URL address rewriting principle is to overwrite the session ID information of the user to the URL address. The server can parse the rewritten URL to obtain the session ID. In this way, you can use session to record user status even if the client does not support cookies. The httpservletresponse class provides encodeurl (string URL) for URL address rewriting. This method automatically determines whether the client supports cookies. If the client supports cookies, the URLs will be output in an intact manner. If the client does not support cookies, the user session ID is rewritten to the URL.

Note: 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 does not carry any cookies (because no cookies can be carried), the URL address after rewriting will still contain the JSESSIONID. When the second access is performed, the server has already written cookies in the browser. Therefore, the URL address after rewriting does not contain the JSESSIONID.

 

3. implement automatic cookie Login

  

Many Web programs do not need to log on again when they access the same web program again within a certain period of time (for example, two hours, instead, you can directly access the main interface of the Program (only on the local machine ). The key to implementing this function is that the server must identify the customer. Cookie is the simplest authentication method.

If you log on for the first time, you can write the user name as a cookie to your local computer. The Code is as follows:

Cookie = new cookie ("user", user );

Cookie. setmaxage (365*24*3600 );

Cookie. setpath ("/");

Response. addcookie (cookie );

When the user accesses the program again, the server program should check whether the cookie exists. The Code is as follows:

Cookie [] cookies = request. getcookies ();

For (Cookie: cookies)

{

If (cookie. getname (). Equals (User ))

{

// If the user cookie exists, process it

Break;

}

}

Although the user cookie can be obtained from the client, the cookie may exist for a long time and it is not safe to log on automatically only with this cookie. Therefore, you can use a session on the server to manage users. That is, after the first successful login, a session is created and some user information is saved in the session. The Code is as follows:

Httpsession session = request. getsession ();

Session. setattribute (user, user );

Session. setmaxinactiveinterval (2*3600); // The session is saved for two hours.

When the program is accessed again, the existence of the cookie is determined, and the existence of the user session will continue to be verified. The Code is as follows:

Cookie [] cookies = request. getcookies ();

For (Cookie: cookies)

{

If (cookie. getname (). Equals (User ))

{

If (session. getattribute (User )! = NULL)

{

// Directly forward to the main interface

Break;

}

Else

{

// Forward to the logon page

}

}

}

Although the above Code can Enable Automatic Logon, when the browser is closed and restarted, The JSESSIONID cookie used by the servlet to save the session ID is temporary (that is, it is not a persistent cookie, when the browser is closed, the cookie will be deleted.) Therefore, JSESSIONID must be persistent. The Code is as follows:

Httpsession session = request. getsession ();

Session. setattribute (user, user );

Session. setmaxinactiveinterval (2*3600); // The session is saved for two hours.

Cookie = new cookie ("JSESSIONID", session. GETID ());

Cookie. setmaxage (2*3600); // The JSESSIONID of the client is also saved for two hours.

Session. setmaxinactiveinterval (interval)

Cookie. setpath ("/");

Response. addcookie (cookie );

 

If the above code is used, even if the browser is closed, the Web application can still log on automatically within two hours.

If we add a JSESSIONID cookie, the HTTP Response Header has two jsessionids when accessing the web application for the first time. However, the two jsessionids have identical values, so there is no impact. If there are multiple identical cookies in the Set-Cookie field of the Response Header, compare them by path and name. If the two values are the same, they are considered to be the same cookie, the last cookie will overwrite the previous one. The following two cookies will overwrite the previous one:

Set-COOKIE: JSESSIONID = ddb2274cac6739e1d6747b0043d5d90e; Path =/Web

Set-COOKIE: JSESSIONID = mysession; expires = Thu, 05-jun-2008 05:02:50 GMT; Path =/Web

Because the following two cookies have different paths, they are two completely different cookies:

Set-COOKIE: JSESSIONID = ddb2274cac6739e1d6747b0043d5d90e; Path =/web1

Set-COOKIE: JSESSIONID = mysession; expires = Thu, 05-jun-2008 05:02:50 GMT; Path =/web2

Other resources: http://blog.csdn.net/ylchou/article/details/7404201

Reference resources: http://blog.csdn.net/zhangxinrun/article/details/5779572

The difference between cookie and session: the session lifecycle,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.