The difference between a session and a cookie

Source: Internet
Author: User
Tags set cookie

The difference between cookie mechanism and session mechanism
In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side.
At the same time, we also see that because the server-side state-of-the-shelf scenario also requires an identity to be stored on the client side, the session mechanism may need to use a cookie mechanism to achieve the purpose of preserving the identity, but there are actually other options

The difference between a session cookie and a persistent cookie
If you do not set an expiration time, the cookie disappears when the browser window is closed as long as the cookie's lifetime is the browser session. This cookie, which has a lifetime of browsing session, is referred to as a session cookie. Session cookies are generally not saved on the hard disk but in memory.
If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and these cookies remain valid until the set expiration time expires.
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 ways of handling them.

How to automate login with implementation
Once a user has registered with a website, they will receive a cookie with a unique user ID. When the customer later reconnect, the user ID is returned automatically, the server checks it, determines whether it is a registered user and chooses automatic login, so that the user's business needs to give an explicit user name and password, you can access the resources on the server.

How to customize the site according to the user's hobby
The website may use cookies to record users ' wishes. For simple settings, the site can store the settings of the page directly in a cookie to complete the customization. For more complex customizations, however, the site simply sends a unique identifier to the user, and the server-side database stores the page settings for each identifier.

Sending of cookies
1. Create a Cookie Object
2. Set Maximum Aging
3. Placing a cookie into the HTTP response header
If you create a cookie and send it to the browser, by default it is a session-level cookie: stored in the browser's memory and deleted after the user exits the browser. If you want the browser to store the cookie on disk, you need to use maxage and give a time in seconds. Setting maximum aging to 0 is the command browser to delete the cookie.
Sending a cookie requires the use of the HttpServletResponse Addcookie method to insert the cookie into a Set-cookie HTTP request header. Since this method does not modify any of the previously specified Set-cookie headers, it creates a new header, so we refer to this method as Addcookie rather than Setcookie. Also remember that the response header must be set before any document content is sent to the client.

Reading of Cookies
1. Call Request.getcookie
To obtain a cookie that is sent by the browser, call HttpServletRequest's GetCookies method, which returns an array of cookie objects corresponding to the value entered by the cookie header in the HTTP request.
2. Loop the array and invoke the GetName method of each cookie until the cookie of interest is found
The cookie is associated with your host (domain), not your servlet or JSP page. Thus, although your servlet may send only a single cookie, you may also get many unrelated cookies.
For example:

[Java]View Plaincopy
  1. String cookiename = "UserID";
  2. Cookie cookies[] = request.getcookies ();
  3. if (cookies!=null) {
  4. For (int i=0;i<cookies.length;i++) {
  5. Cookie cookie = cookies[i];
  6. if (Cookiename.equals (Cookie.getname ())) {
  7. Dosomethingwith (Cookie.getvalue ());
  8. }
  9. }
  10. }

How to use cookies to detect first-person visitors
A. Call Httpservletrequest.getcookies () to get an array of cookies
B. Retrieving a cookie for a specified name in a loop exists and the corresponding value is correct
C. If yes, exit the loop and set the differential ID
D. Determine whether the user is a novice and perform different operations according to the distinguishing mark

It is important to note that

You cannot think of a user as a novice simply because the cookie array does not exist in a particular data item. If the cookie array is null, the customer may be a novice, or it may be the result of a user deleting or disabling the cookie.
However, if the array is not NULL, it simply shows that the client has been to your site or domain and does not indicate that they have visited your servlet. Other Servlets, JSP pages, and non-Java Web Apps can set cookies, depending on the path setting, where any cookie is likely to be returned to the user's browser.
The correct approach is to determine if the cookie array is empty and the specified cookie object exists and the value is correct.

Notes on using cookie attributes
Properties are part of the header that is sent from the server to the browser, but they do not belong to the header returned to the server by the browser.
Therefore, in addition to the name and value, the cookie attribute applies only to cookies exported from the server to the client, and the server-side cookie from the browser does not have these attributes set.
This property is therefore not expected to be available in cookies obtained through request.getcookies. This means that you cannot simply set the cookie's maximum age, issue it, look for the appropriate cookie in the subsequent input array, read its value, modify it, and save it back to the cookie to achieve the changing cookie value.

How to use cookies to record access counts for individual users
1. Get the value of the cookie in the cookie array specifically used to count the number of user visits
2. Convert values to int type
3. Add a value of 1 and recreate a cookie object with the original name
4. Reset Maximum Aging
5. Export the new cookie

Cookie cross-domain operation

A normal cookie can only be shared in one app, meaning that a cookie can only be obtained by the app that created it.

    1. The method can be shared within the same application server: Set Cookie.setpath ("/");        native tomcat/ WebApp There are two applications: CAs and webapp_b,        1) The cookies that were originally set under CAs are not available under Webapp_b, Path is the default for the application that generated the cookie.         2) If you set a cookie under CAs, add a cookie.setpath ("/"), or Cookie.setpath ("/ webapp_b/"), you can get the cookie set by CAS under Webapp_b.         3) The parameters here are relative to the root directory of the folder where the application server holds the app (for example, WebApp under Tomcat), so Cookie.setpath ("/"), after which the cookie can be shared with all apps under the WebApp folder, and Cookie.setpath ("/webapp_b/"), which means that the cookie set by the CAs app is only available under the Webapp_b app, Even CAS applications that produce this cookie are not allowed.         4) Set Cookie.setpath ("/webapp_b/jsp") or Cookie.setpath ("/webapp_b/jsp/" ), cookies can only be obtained under webapp_b/jsp, but cannot be obtained under webapp_b but outside of the JSP folder.         5) Set Cookie.setpath ("/webapp_b"), which means that cookies can be used under Webapp_b, This will not allow cookies to be obtained under the application CAs that generate cookies         6) There are several Cookie.setpath ("XXX "); When the statement is made, the last rule will prevail.         7) How to set multiple path???      2. How to share cookies across domains: Set Cookie.setdomain (".");         A machine in the same domain:,a has the domain where the cas        b machine is applied:,b has an application webapp_b         1) Add Cookie.setdomain (".") when setting cookies under CAs, so that in Webapp_ b You can take a cookie below.         2) This parameter must be "." Begin.         3) When you enter a URL to access webapp_b, you must enter the domain name to resolve. For example, in a machine input:, you can get the cookie set by the CAs at the client, and the B machine accesses the application of this machine, enter:http://localhost:8080/webapp_bYou may not receive cookies.        4) Cookie.setdomain (".") is set, and can also be shared under the default 5) How to set up multiple domains???

Different meanings of the session in different environments
Session, Chinese is often translated into a conversation, its original meaning refers to the beginning and end of a series of actions/messages, such as the call is from the pick up the phone to dial to hang up the phone in the middle of a series of processes can be called a session.
However, when the term session is associated with a network protocol, it often implies two meanings such as "connection oriented" and/or "hold State".
The semantics of the session in the Web development environment also has a new extension, meaning refers to a class of solutions to maintain state between the client and the server side. Sometimes the session is used to refer to the storage structure of this solution.

The mechanism of the session
The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.
However, 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 it already contains a session The ID indicates that the previous session has been created for this customer, the server will follow the session ID to retrieve the session (if it is not retrieved, may create a new one, this situation may appear on the service side has deleted the user corresponding Session object, However, the user manually appends the previous jsession parameter to the requested URL.
If the customer request does not include a session ID, a session is created for the customer and a session ID associated with the session is generated, and the session ID is returned to the client in this response.

Several ways to save session IDs
A You can save the session ID by using a cookie so that the browser can automatically send the tag to the server in the interactive process.
B Since cookies can be artificially banned, there must be other mechanisms to pass the session ID back to the server when the cookie is banned, a technique often called URL rewriting, which appends the session ID to the URL path, with two additional ways, One is additional information as a URL path, and the other is appended to the URL as a query string. The network always maintains state throughout the interaction and must include the session ID after each client may request a path.
C Another technique is called a form-hidden field. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted.

What are the drawbacks of URL rewriting
Use URL overrides for all URLs, including hyperlinks, action for form, and redirected URLs. Each URL that references your site, and the URLs that are returned to the user (even through indirect means, such as the Location field in server redirection), add additional information.
This means that you cannot have any static HTML pages on your site (at least static pages cannot have any links to site dynamic pages). Therefore, each page must be dynamically generated using a servlet or JSP. Even if all the pages are generated dynamically, if the user leaves the session and comes back again via a bookmark or link, the session information is lost because the stored link contains the wrong identity information-the session ID after the URL has expired.

What are the drawbacks of using hidden form fields
You can use this method only if each page is dynamically generated with a form submission. Click the General <a HREF: > Hypertext links do not generate form submissions, so hidden form fields cannot support normal session tracking, only for a specific set of operations, such as the checkout process for an online store

When was the session created?
A common mistake is that the session is created when there is client access, but the fact is that it is not created until a statement such as Httpservletrequest.getsession (true) is called by a server-side program, such as a servlet.

When the session was deleted
The session is deleted under the following circumstances:
A Program Call Httpsession.invalidate ()
B Distance from the last received client sent session ID time interval exceeds the maximum effective time of the session
C Server process is stopped
Note that closing the browser only invalidates the session cookie stored in the client browser memory and does not invalidate the session object on the server side.

GetSession ()/getsession (True), getsession (false) differences
GetSession ()/getsession (TRUE): Returns the session when the session exists, or creates a new session and returns the object
GetSession (FALSE): Returns the session when the session is present, otherwise does not create a new session and returns null

Basic steps for session tracking
1. Accessing the Session object associated with the current request
2. Find information about a session
3. Storing session information
4. Discard session Data

How to relate information to a session
SetAttribute replaces any previously set value, and if you want to remove a value without providing any substitution, you should use RemoveAttribute. This method triggers all Valueunbound methods that implement the value of the Httpsessionbindinglistener interface.

Are there any restrictions on the types of session properties?
Usually the type of session attribute is as long as an object is available. Except for null or basic types, such as Int,double,boolean.
If you want to use the value of the base type as an attribute, you must convert it to the corresponding encapsulated class object

How to discard session data
A Remove only the data created by the servlet you wrote:
Call RemoveAttribute ("key") to discard the value associated with the specified key
B Delete the entire session (in the current web app):
Call invalidate to discard the entire session. Doing so will lose all session data for that user, not just session data created by our servlet or JSP pages
C Log off the user from the system and delete all sessions that belong to him or her
Call logout to log off the client from the Web server and discard all sessions associated with that user (at most one per web app). This can affect several different Web applications on the server

Use IsNew to determine if a user is wrong with a new or old user
public Boolean IsNew () method This method returns true if the session has not been associated with the client program (browser), typically because the session is new and not caused by the input client request.
However, if IsNew returns false, it simply means that he has visited the Web app before and does not mean that they have visited our servlet or JSP pages.
Because the session is user-related, it is possible for each page accessed by the user to create a conversation. So isnew to false can only say that the user has previously visited the Web app, the session can be either the current page creation, or the user previously visited the page created.
The right thing to do is to determine if a particular key exists in a session and its value is correct

What is the difference between the expiration of a cookie and the timeout of a session
The timeout for a session is maintained by the server, which differs from the expiration date of the cookie.

First, sessions are generally based on memory-resident cookies, not persistent cookies, and thus have no deadlines.

Even if the Jsessionid cookie is intercepted and set an expiration date for it to be sent out. Browser sessions and server sessions are also very different.

is the session cookie the same as the lifetime of the session object?
When the user closes the browser while the session cookie has disappeared, the session object is still stored on the server side

If you close the browser, the session disappears.
The program is usually when the user does log off to send a command to delete the session, however, the browser will never proactively notify the server before closing it will be shut down, so the server will not have the opportunity to know that the browser has been closed. The server retains the session object until it is inactive beyond the set interval.
The reason for this error is that most sessions use session cookies to save the conversation ID, and this session ID disappears when you close the browser, and you cannot find the original session when you connect to the server again.
If the cookie set by the server is saved to the hard disk, or if you use some means to overwrite the HTTP request header sent by the browser, send the original session ID to the server, then open the browser again to still be able to find the original session.
It is precisely because closing the browser does not cause the session to be deleted, forcing the server to set an expiration time for the session, when the customer last time to use the session more than the expiration time, the server can assume that the client has stopped the activity, The session is deleted to save storage space.
From this we can draw the following conclusions:
Closing the browser will only leave the session cookie in the browser's memory, but it will not disappear from the session object saved on the server side, nor will the persistent cookie that has been saved to the hard disk disappear.

Open two browser windows access the application using the same session or a different session
Usually the session cookie is not used across windows, and when you open a new browser window to the same page, the system will give you a new session ID, so that the purpose of our information sharing is not reached.
At this point we can first save the session ID in the persistent cookie (by setting the session's maximum effective time), and then read it in a new window, you can get the session ID of the previous window, so that through the session The combination of a cookie and a persistent cookie allows us to implement a cross-window session trace.

How to use sessions to show the number of visits per customer
Since the client's access count is an integer variable, it is not possible to use basic types of variables such as Int,double,boolean in the session's attribute type, so we use these basic types of encapsulated type objects as the values of the properties in the Session object
But like an integer is a non-modifiable (immutable) data structure that cannot be changed after it is built. This means that each request must create a new integer object, and then use setattribute instead of the value of the old property that existed earlier. For example:

[Java]View Plaincopy
    1. httpsession session = request.getsession ();   
    2. someimmutalbeclass value =  (someimmutableclass) Session.getattribute (" Someidentifier ");   
    3. if  (value= = null) {  
    4.      value = new someimmutableclass (...); //  create a new immutable object   
    5. }else{   
    6.      value = new  Someimmutableclass (Calculatedfrom (value));  //  create new object after value recalculation   
    7. }&NBSP;&NBSP;
    8. session.setattribute ("Someidentifier", value);  < span class= "comment" >//  overwrites the old object    with the newly created object;

How to use a session to accumulate user data
Use variable data structures, such as arrays, lists, maps, or application-specific data structures that contain write-in segments. In this way, you do not need to call setattribute unless you assign the object for the first time. For example

[Java]View Plaincopy
    1. HttpSession session = Request.getsession ();
    2. Somemutableclass value = (somemutableclass) session.getattribute ("Someidentifier");
    3. if (value = = null) {
    4. Value = new Somemutableclass (...);
    5. Session.setattribute ("Someidentifier", value);
    6. }else{
    7. Value.updateinternalattribute (...); //If the object already exists, update its properties without having to reset the property
    8. }

Non-changing objects and the different handling of changed objects when session data is updated
Object cannot be changed because it cannot be changed once it is created, so every time you want to modify the value of a property in a session, you need to call setattribute ("Someidentifier", NewValue) instead of the value of the original property. Otherwise, the value of the property is not updated to change the object because it typically provides a way to modify its own properties, so whenever you want to modify the value of a property in a session, you can simply call the method that modifies the property of the object that can be changed. This means that we don't need to call the SetAttribute method.

The difference between a session and a cookie

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