How to distinguish different user--cookie/session mechanism detailed

Source: Internet
Author: User
Tags base64 sessions

Session tracking is a common technique used in Web programs to track the entire session of a user. Common session-tracking techniques are cookies and sessions. The cookie determines the user identity by logging information on the client, and the session determines the user identity by logging information on the server side.

This chapter will systematically describe the cookie and session mechanism, and compare when you can't use cookies and when to use session.

1.1 Cookie Mechanism

In a program, session tracking is a very important thing. Theoretically, all request operations of a user should belong to the same session, and all request operations of another user should belong to another session, which cannot be confused. For example, any item purchased by user A in a supermarket should be placed in a shopping cart, regardless of when user a purchased it, which belongs to the same session, and cannot be placed in User B or User C's shopping cart, which is not part of the same session.

The Web application transmits data using the HTTP protocol. The HTTP protocol is a stateless protocol. Once the data is exchanged, the connection between the client and the server is turned off, and a new connection is required to exchange the data again. This means that the server cannot track the session from the connection. That is, user a buys a product into a shopping cart, and the server is unable to determine whether the purchase behavior belongs to user A's session or User B's session when the item is purchased again. To track the session, you must introduce a mechanism.

Cookies are such a mechanism. It can make up for the lack of state of HTTP protocol. Almost all Web sites use cookies to track sessions before the session appears.

1.1.1 What is a cookie

Cookie means "cookie", which was put forward by the organization of the Consortium, and was the first mechanism developed by Netscape community. Cookies are now standard, and all major browsers such as IE, Netscape, Firefox, opera, and so on, support cookies.

Because HTTP is a stateless protocol, the server alone does not know the identity of the customer from the network connection. How to do it. Give the client a pass bar, each person, no matter who visit must carry their own pass. This will enable the server to confirm the identity of the customer from the pass. That's how cookies work.

A cookie is actually a small piece of textual information. The client requests the server, and if the server needs to log that user state, use response to issue a cookie to the client browser. The client browser will save cookies. When the browser requests the site again, the browser submits the requested URL along with the cookie to the server. The server checks the cookie to identify the user status. The server can also modify the contents of the cookie as needed.

It is easy to view cookies issued by a Web site. Enter Javascript:alert (document. cookie) in the browser address bar (you need a network to view it). The JavaScript script pops up a dialog box that displays the contents of all cookies issued on this site, as shown in Figure 1.1.

Figure 1.1 Baidu Web site issued cookies

Figure 1.1 The pop-up dialog box shows a cookie for the Baidu Web site. One of the first line Baiduid record is the author's identity Helloweenvsfei, but Baidu uses a special method to encrypt the cookie information.

Note: The cookies feature requires browser support.

If the browser does not support cookies (such as the browser on most phones) or disables cookies, the cookie function will fail.

Different browsers save cookies in different ways.

IE browser will be saved as a text file under "C:\Documents and Settings\ your username \cookies" folder, a text file to save a cookie.

1.1.2 Record number of user visits

In Java, the cookie is encapsulated into a Javax.servlet.http.Cookie class. Each cookie is an object of that cookie class. The server operates on the client cookie by manipulating the cookie class object. by Request.getcookie () get all cookies submitted by the client (as a cookie[] array, the cookie is set to the client via Response.addcookie (Cookiecookie).

The cookie object holds the user state in the form of a Key-value property pair, and a cookie object holds a property pair, and a request or response uses multiple cookies at the same time. Because the cookie class is under the package javax.servlet.http.*, you do not need to import the class in the JSP.

Non-cross domain name of 1.1.3 Cookies

Many websites use cookies. For example, Google issues Cookie,baidu to clients and also issues cookies to clients. The browser to visit Google will also carry the cookies issued by Baidu. Or Google can modify the cookies issued by Baidu.

The answer is in the negative. Cookies have no Cross-domain domain name. According to the cookie specification, browser access to Google will only carry Google cookies, and will not carry the Baidu cookie. Google can only operate Google cookies, but not the Baidu cookie.

Cookies are managed by the browser at the client. The browser can guarantee that Google will only operate Google cookies and will not operate the Baidu Cookie, thus ensuring the privacy of the user. The browser determines whether a Web site can operate another site cookie based on the domain name. Google and Baidu's domain name is not the same, so Google can not operate Baidu's cookies.

It should be noted that although the site and site belong to Google, but the domain name is not the same, both can not operate each other's cookies.

Note: When a user logs on to a Web site, the login information is still valid when accessing, and ordinary cookies are not. This is because Google does a special deal. Cookies will also be treated similarly in the following chapter.

1.1.4 Unicode encoding: Saving Chinese

Unlike English characters, Chinese is a Unicode character and occupies 4 characters in memory, while English is an ASCII character and occupies only 2 bytes in memory. Unicode characters need to be encoded when using Unicode characters in cookies, otherwise they will be garbled.

Hint: Chinese can only be encoded in cookies. UTF-8 encoding is generally used. Chinese encoding such as GBK is not recommended because browsers are not necessarily supported and JavaScript does not support GBK encoding.

1.1.5 BASE64 encoding: Saving binary pictures

Cookies can use not only ASCII characters and Unicode characters, but also binary data. For example, the use of digital certificates in cookies provides security. Encoding is also required when using binary data.

% Note: This program is only used to show cookies can store binary content, not practical. Because the browser will carry cookies every time the server requests it, the cookie content should not be too much, or affect the speed. The contents of cookies should be few and few.

1.1.6 set all properties of a cookie

In addition to name and value, cookies have several other common properties. Each attribute corresponds to a getter method and a setter method. All of the properties of the cookie class are shown in Table 1.1.

Table 1.1 Cookie Common Properties

Property name


String Name

The name of the cookie. Once the cookie is created, the name cannot be changed

Object value

The value of the cookie. If the value is a Unicode character, you need to encode the character. If the value is binary data, you need to use the BASE64 encoding

int MaxAge

The time, in seconds, that the cookie was invalidated. If a positive number, the cookie expires after maxage seconds. If it is a negative number, the cookie is a temporary cookie, and the browser does not save the cookie in any form. If 0, indicates that the cookie is deleted. Default is –1

Boolean secure

Whether the cookie is only transmitted using a secure protocol. Security protocols. Security protocols have HTTPS,SSL, etc., to encrypt data before transferring data over the network. Default to False

String Path

The use path of the cookie. If set to "/sessionweb/", only programs with ContextPath "/sessionweb" can access the cookie. If set to "/", the cookie is accessible to contextpath under this domain name. Note that the last character must be "/"

String Domain

The domain name of the cookie can be accessed. If set to., the cookie is accessible to all domain names that end with "". Note that the first character must be "."

String Comment

A description of the usefulness of the cookie. Display the description when the browser displays cookie information

int version

The version number used by the cookie. 0 indicates compliance with Netscape's Cookie specification, and 1 indicates compliance with the RFC 2109 specification of the Consortium

Validity of 1.1.7 Cookies

The maxage of the cookie determines the validity of the cookie, in seconds (Second). The MaxAge property is read and written by the Getmaxage () method and the setmaxage (int maxage) method in the cookie.

If the MaxAge property is a positive number, it means that the cookie will automatically expire after maxage seconds. The browser persists the cookie maxage as a positive, which is written to the corresponding cookie file. Whether the customer closes the browser or the computer, the cookie is still valid as long as it is maxage seconds before logging on to the site. The cookie information in the following code will always be valid.

Cookie cookie = new Cookie ("username", "Helloweenvsfei"); New Cookie

Cookie.setmaxage (Integer.max_value); Set life cycle to Max_value

Response.addcookie (cookie); Output to Client

If MaxAge is a negative number, it means that the cookie is valid only in this browser window and in the child window that is open in this window, and the cookie is invalidated when the window is closed. A maxage is a negative cookie that is a temporary cookie and is not persisted and will not be written to a cookie file. The cookie information is stored in browser memory, so the cookie disappears when you close the browser. The default MaxAge value for the cookie is –1.

If MaxAge is 0, the cookie is deleted. The cookie mechanism does not provide a way to delete cookies, so the effect of deleting cookies is achieved by setting the cookie's immediate expiration. Invalid cookies are removed by the browser from the cookie file or memory.

For example:

Cookie cookie = new Cookie ("username", "Helloweenvsfei"); New Cookie

Cookie.setmaxage (0); Set life cycle to 0, not negative

Response.addcookie (cookie); This sentence must be implemented

The cookie action method provided by the response object has only one add operation Add (Cookie cookie).

To modify a cookie, you can only use a cookie with the same name to overwrite the original cookie for the purpose of the modification. Delete only need to change the maxage to 0.

Note: When you read cookies from the client, other properties, including MaxAge, are unreadable and will not be committed. The name and Value property are only submitted when the browser submits the cookie. The MaxAge property is used only by the browser to determine whether the cookie expires.

Modification and deletion of 1.1.8 cookies

Cookies do not provide modify, delete operations. If you want to modify a cookie, simply create a new cookie with the same name and add it to the response to overwrite the original cookie.

To delete a cookie, simply create a new cookie with the same name and set the MaxAge to 0 and add it to the response to overwrite the original cookie. Note that 0 is not a negative number. Negative numbers represent other meanings. Readers can use the program in the example to verify that different properties are set.

Note: When modifying and deleting cookies, the new cookie will be exactly the same as the original cookie except value, MaxAge, such as name, path, domain, and so on. Otherwise, the browser will be treated as two different cookies without overwriting, causing the modification and deletion to fail.

1.1.9 Cookie's domain name

A cookie is not a cross-domain domain name. The cookie issued by the domain will not be submitted to the domain This is determined by the privacy security mechanism of the cookie. Privacy security can prevent websites from illegally acquiring cookies from other websites.

Under normal circumstances, the same level of domain name two level two domain names such as and can not use cookies, because the domain name is not strictly the same. If you want to use the cookie for all level two domains in the name, you need to set the domain parameter for the cookie, for example:

Cookie cookie = new Cookie ("Time", "20080808"); New Cookie

Cookie.setdomain ("."); Setting the domain name

Cookie.setpath ("/"); Set path

Cookie.setmaxage (Integer.max_value); Set Expiration

Response.addcookie (cookie); Output to Client

Readers can modify the hosts file under the local C:\WINDOWS\system32\drivers\etc to configure multiple temporary domain names, and then use the SETCOOKIE.JSP program to set the cross domain cookie to authenticate domain properties.

Note: The domain parameter must be a dot (".") Begin. In addition, two cookies with the same name but domain differ from two different cookies. If you want two domain names that are completely different to a common cookie, you can generate two Cookie,domain properties of two domain names, output to the client.

Path to 1.1.10 Cookie

The domain property determines the name at which to run the access cookie, and the Path property determines the paths that allow access to the cookie (contextpath). For example, if you only allow a program under/sessionweb/to use cookies, you can write this:

Cookie cookie = new Cookie ("Time", "20080808"); New Cookie

Cookie.setpath ("/session/"); Set path

Response.addcookie (cookie); Output to Client

All paths are allowed to use cookies when set to "/". The path attribute needs to end with the symbol "/". Two cookies with the same name but domain are also two different cookies.

Note: The page can only get cookies for the path it belongs to. For example,/session/test/a.jsp cannot get a cookie with a path of/session/abc/. Be sure to pay attention when using.

Security properties for 1.1.11 cookies

The HTTP protocol is not only stateless, but also unsafe. Data using the HTTP protocol is transmitted directly over the network without any encryption, and there is the possibility of interception. Using the HTTP protocol to transmit very confidential content is a hidden danger. If you do not want cookies to be transmitted in unsecured protocols such as HTTP, you can set the secure property of the cookie to true. Browsers only transmit such cookies in secure protocols such as HTTPS and SSL. The following code sets the secure property to true:

Cookie cookie = new Cookie ("Time", "20080808"); New Cookie

Cookie.setsecure (TRUE); Setting security properties

Response.addcookie (cookie); Output to Client

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.