The difference between cookie and session and the life cycle of the session

Source: Internet
Author: User
Tags session id sessions java web server memory

These are basic knowledge, but it is necessary to do a thorough understanding. Let's start with a brief introduction.

the definition of the two:

When you are browsing the Web, the Web server will send a small piece of information to your computer, and the Cookie will help you record the text or some choices you make on the site. The next time you visit the same site, the Web server will first see if it has left the cookie data, if so, will be based on the contents of the cookie to judge the user, send a specific page content to you. The use of cookies is common, and many Web sites that provide personalized services use cookies to identify users to facilitate the delivery of user-tailored content, such as a free email web interface, using cookies.


Specifically, the cookie mechanism is a scheme for maintaining state on the client side, and the session mechanism uses the scheme of maintaining state at the server end.

At the same time, we also see that because the server-side retention scheme also needs to be stored in the client, the session mechanism may need to use the cookie mechanism to save the identity, but in fact it has other options.

Cookie mechanism. Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, pure client script such as JavaScript or VBScript can also generate cookies. And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and sends the cookie to the server on the HTTP request header of the requesting resource if the cookie is declared to be more than equal to the location of the resource being requested.

The contents of the cookie mainly include: name, value, expiration time, path and domain. A path, together with a domain, forms the scope of the cookie. If you do not set an expiration time, the lifetime of this cookie is the period of the browser session, the cookie disappears when the browser window is closed. This lifetime is known as a session cookie for a browser session-time cookie.

Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated by the specification. If the expiration time is set, the browser saves the cookie to the hard disk, closes it and opens the browser again, and the cookies are still valid until the expiration date is exceeded. Cookies stored on your hard disk can be shared between different browser processes, such as two IE windows. And for cookies stored in memory, different browsers have different ways of handling the session mechanism. The session mechanism is a server-side mechanism in which the server uses a structure similar to a hash table (or perhaps a hash table) to hold the information.

When a program needs to create a session for a client's request, the server first checks to see if the client's request already contains a session ID (called a session ID.), or if it has already been previously created for this client, The server retrieves this session using the sessions ID (not retrieved, creates a new one), creates a session for this client, and generates an event ID that is associated with the session if the client request does not contain a session ID. The value of the session ID should be a string that is not duplicated and is not easy to be found, and will be returned to the client for saving in this response. This session ID can be saved in a cookie, so that the browser can automatically send the identity to the server according to the rules during the interaction. Generally this cookie's name is similar to Seeesionid. However, cookies can be artificially prohibited, and there must be other mechanisms to pass the session ID back to the server when the cookie is blocked.

One technique that is often used is called URL rewriting, which is to attach the session ID directly behind the URL path.

There is also a technique called form hidden fields. The server will automatically modify the form and add a hidden field so that the session ID can be passed back to the server when the form is submitted. Like what:
<form name= "Testform" action= "/xxx" >
<input type= "hidden" name= "Jsessionid" value= "byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764" >
<input type= "Text" >
</form>
In fact, this technique can be simply replaced by applying URL rewriting to the action.


the difference between a cookie and a session:

1, the cookie data stored in the customer's browser, session data on the server.

2, cookies are not very safe, others can analyze stored in the local cookies and cookie spoofing, taking into account the security should use session.

3, session will be stored in a certain period of time on the server. When the access is increased, the performance of your server is compared, and cookies should be used to mitigate server performance.

4, a single cookie can not save more than 4K of data, many browsers limit a site to save up to 20 cookies.

5, so personal recommendations:
The log information and other important information stored as session.
Additional information, if required, can be placed in a cookie.

the life cycle of the session

Session is stored on the server side, generally in order to prevent in the server's memory (for high-speed access), Sessinon when the user accesses the first access to the server, you need to be aware that only access to the JSP, servlet and other programs will create sessions, only access to HTML, Static resources such as image do not create a session, and you can invoke Request.getsession (true) to force a session to be generated.

when does the session expire?

1. The server will remove the session from the server memory for a long period of time without activity, and the sessions will fail. The default expiration time for a session in Tomcat is 20 minutes.

2. Call the Invalidate method of the session.

Session Requirements for browsers:

Although the session is saved on the server and is transparent to the client, its normal operation still requires the support of the client browser. This is because the session needs to use a cookie as the identification flag. The HTTP protocol is stateless, the session cannot be judged by the HTTP connection to be the same customer, so the server sends a cookie named Jsessionid to the client browser. Its value is the ID of the session (that is, the return value of Httpsession.getid ()). The session is based on the cookie to identify whether it is the same user.

This cookie is automatically generated for the server, and its MaxAge property is typically-1, which means that only the current browser is valid, and the browser windows are not shared, closing the browser will fail. So when the two browser windows of the same machine access the server, two different sessions are generated. Except for open windows that are opened by links, scripts, and so on in the browser window (that is, not double-clicking the desktop browser icon). This type of child window shares the parent window's cookie, so a session is shared.

Note: The new browser window generates a new session, except for child windows. Child Windows share the session of the parent window. For example, when you right-click on a link and choose Open in New Window on the pop-up shortcut menu, the child window can access the parent window's session.

What if the client browser disables the cookie feature or does not support cookies? For example, the vast majority of mobile browsers do not support cookies. The Java Web provides another solution: URL-Address rewriting.

URL address Rewriting is a solution to a client that does not support cookies. The principle of URL address rewriting is to rewrite the ID information of the user session to the URL address. The server is able to resolve the overridden URL to get the session ID. This allows you to use the session to record user status even if the client does not support cookies. The HttpServletResponse class provides a encodeurl (String URL) that implements URL address rewriting, which automatically determines whether the client supports cookies. If the client supports cookies, the URL is exported intact. If the client does not support cookies, the ID of the user session is rewritten into the URL.

Attention:

Tomcat determines whether the client browser supports cookies based on whether the request contains cookies. Although the client may support cookies, the address after the URL rewrite will still be jsessionid, because the first request does not carry any cookies (since no cookies can carry them). When the server has written a cookie in the browser for the second visit, the URL address is rewritten without jsessionid.

Implement automatic Login Cookies  

There are many web programs in the first logon, within a certain period of time (such as 2 hours) to access the same Web program again without having to log on again, but directly into the program's main interface (only local). The key to implementing this function is to identify the customer by the server. and using cookies is the easiest body to verify from.

If a user logs on for the first time, the user name can be written locally as a cookie, and the code is as follows:

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

Cookie.setmaxage (365 * 24 * 3600);

Cookie.setpath ("/");

Response.addcookie (cookie);

When the user accesses the program again, the server-side program should detect if the cookie exists and the code is as follows:

Cookie[] Cookies=request.getcookies ();

for (Cookie cookie:cookies)

{

if (Cookie.getname (). Equals (user))

{

If the user cookie exists and is processed

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 with this cookie, so you can use a session on the server to manage the user. That is, when the first login succeeds, it creates a session and saves some of the user's information in session. The code is as follows:

HttpSession session =request.getsession ();

Session.setattribute (user, user);

Session.setmaxinactiveinterval (2 * 3600); Session Save two hours


When the program is accessed again, when the cookie is identified, it continues to verify the presence of the user session with the following code:

Cookie[] Cookies=request.getcookies ();

for (Cookie cookie:cookies)

{

if (Cookie.getname (). Equals (user))

{

if (session.getattribute (user)!= null)

{

Direct forward to the main interface

Break

}

Else

{

Forward to login interface

}

}

}


Although the above code can implement the automatic login function well, when the browser closes and starts again, the Jsessionid cookie that the servlet uses to save the session ID is temporary (that is, it is not a persistent cookie, and when the browser closes, This cookie is deleted), so the jsessionid need to be persisted. The code is as follows:

HttpSession session = Request.getsession ();

Session.setattribute (user, user);

Session.setmaxinactiveinterval (2 * 3600); Session Save two hours

Cookie cookie = new Cookie ("Jsessionid", Session.getid ());

Cookie.setmaxage (2 * 3600); Client Jsessionid also saved for two hours

Session.setmaxinactiveinterval (interval)

Cookie.setpath ("/");

Response.addcookie (cookie);

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


If we own a jsessionid Cookie, the HTTP response header has two jsessionid for the first time we access the Web program, but because the values of these two jsessionid are exactly the same, there is no effect. If there are multiple identical cookies in the Set-cookie field of the response header, compare the path to name, and if the two values are the same, consider the same cookie, and the last cookie that appears will overwrite the same cookie in front of it. As the following two cookies, the last one 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 path of the following two cookies is different, they are completely different two 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



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.