Cookie and session difference, session life cycle,

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 cookies will help you with the text or some choices you make on the site,

are recorded. The next time you visit the same site, the Web server will see if there is any cookie information that it left last, and if so, it will be based on the cookie

Content to judge users, send out specific Web content to you. The use of cookies is common, and many Web sites that offer personalized services are using cookies

To identify users, to facilitate the delivery of user-tailored content, such as the Web interface of the free email site, to use 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 the session mechanism may need to use the cookie mechanism because the server-side retention scheme is also required to store an identity at the client.

To achieve the purpose of saving 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 prompts by adding a special line of instructions to the HTTP response header

The browser generates the appropriate cookie as instructed. However, pure client script such as JavaScript or VBScript can also generate cookies. And the use of cookies

is by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies, and if a cookie declares a scope

is greater than or equal to the location of the resource being requested, the cookie is attached to the server on the HTTP request header of the requesting resource.

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, it indicates that this

The lifetime of a cookie is the time 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 will put the cookie

Save to your hard disk, and then open the browser again after closing, and the cookies will still be valid until you exceed the expiration time you set. Cookies stored on the hard disk can be in different bangs

Browsing process sharing, such as two IE windows. And for cookies stored in memory, different browsers have different ways of handling

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 contains a session ID

(called the session ID), if already included, the server retrieves the session by the session ID, if it has previously created a session for this client

Used (not retrieved, a new one is created), if the client request does not contain a session ID, create a session for the client and generate a session

The value of the associated session Id,session ID should be a string that is neither duplicated nor easily found to mimic, and this session ID will be in this response

is returned to the client for saving. The way to save this session ID is to use a cookie so that the browser can automatically send the logo to the following rules in the interactive process

Server. Generally this cookie's name is similar to Seeesionid. But cookies can be artificially prohibited, and there must be other mechanisms for the cookie to be disabled

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

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. is the server

Automatically modifies the form and adds a hidden field to allow the session ID to 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
Consider that security should use session.

3, session will be stored in a certain period of time on the server. When the visit increases, it will take up the performance of your server
Consider the use of cookies for mitigating 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:
Storing important information such as login information as session
Additional information, if required, can be placed in a cookie

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

Note: 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.

Three. Implement automatic login Cookie

  

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.