Session Tracker Cookie

Source: Internet
Author: User

Session tracking

Session tracking is a common technique used in Web programs to track a user's entire session. Commonly used session tracking technology for cookies and sessions. The cookie determines the user's identity by logging information on the client , and the session determines the user's identity by logging information on the server side .

The theory is that all request actions for one user should belong to the same session, while all request actions of another user should belong to another session, and they should not be confused. The Web application transmits data using the HTTP protocol. The HTTP protocol is a stateless protocol. Once the data has been exchanged, the client-to-server connection is closed, and exchanging the data again requires establishing a new connection. This means that the server is unable to track the session from the connection. To track this session, you must introduce a mechanism. Cookies and sessions are such a mechanism.

1. Cookies

1.1 Cookie Definition

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

It's easy to see the cookies issued by a website. After accessing the site's page in the browser, enter Javascript:alert (document.cookie) in the browser address bar, and the JavaScript script pops up a dialog box showing the contents of all cookies issued on this site.

Note : The cookie feature requires browser support. If the browser does not support cookies or if the cookie is disabled, the cookie function will expire. Different browsers use different ways to save cookies.

Basic use of 1.2 cookies in Java EE

In Java, the cookie is encapsulated into the Java.servlet.http.Cookie class. Each cookie is an object of the cookie class. The server operates on the client cookie by manipulating the cookie class object. Get all cookies submitted by the client (in cookie[] array) via Request.getcookies (), via Response.addcookie (Cookiecookie) Set a cookie to the client.

The cookie object saves the user state in the form of a Key-value property pair, a cookie object that holds a property pair , and a request or response uses multiple cookies at the same time.

1.2.1 Get cookies on server side

Cookie[]cookies = Request.getcookies ();

for (int i = 0; cookies = null && i < cookies.length;i++) {

Cookiecookie = Cookies[i];

if ("username". Equals (Cookie.getname ())) {



1.2.2 Setting cookies on the server side

Stringusername = "sa";

Cookieusernamecookie = new Cookie ("username", username);

Response.addcookie (Usernamecookie);

1.3 The non-cross domain name of cookies

Cookies have non-cross-domain names. According to the cookie specification, browser access to Google only carries Google's cookies and does not carry Baidu's cookies. Google can only operate Google's cookies and not operate Baidu's cookies.

Cookies are managed by the browser on the client side. The browser can guarantee that Google will only operate Google's cookies without manipulating Baidu's cookies, thereby ensuring the privacy of the user. The browser determines whether a website can operate on another site cookie based on the domain name. Google does not have the same domain name as Baidu, so Google cannot manipulate Baidu's cookies.

1.4 Unicode Encoding

Unicode characters are encoded in a cookie when Unicode characters are used, or garbled. Encoding can use the Encode (Stringstr,string encoding) method of the class to decode using the Decode class (String str,string Encoding) method.

Coding Examples:

Cookiecookie = new Cookie ("username", Urlencoder. Encode("Mei", "UTF-8"));

Response.addcookie (cookie);

decoding Example:

Cookie[]cookies = Request.getcookies ();

for (int i = 0; cookies = null && i < cookies.length; i++) {

Cookiec = Cookies[i];

if ("username". Equals (C.getname ())) {

Stringusername = Urldecoder. Decode (C.getvalue (), "UTF-8");



1.5 Setting all properties of a cookie

String Name

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

Object value

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

int MaxAge

The time, in seconds, at which the cookie expires. If positive, the cookie expires after maxage seconds. If it is a negative number, the cookie is a temporary cookie and the browser is deactivated and the browser does not save the cookie in any way. If 0, the cookie is deleted. The default is-1.

Boolean secure

Whether the cookie is only transmitted using security protocols. The security protocol has HTTPS, SSL, and so on, the data is encrypted before the data is transmitted on the network, the default is False. This property does not encrypt the cookie content and therefore does not guarantee absolute security. If high security is required, the cookie content needs to be encrypted and decrypted in the program.

String Path

The path to use for the cookie. If set to "/sessionweb/", only programs with ContextPath "/sessionweb" can access the cookie. If set to "/", the cookie can be accessed by ContextPath under this domain name. Note the first character must be "/".

String Domain

The domain name in which the cookie can be accessed. If set to ".", all domain names ending with "" can access the cookie. Note the first character must be ".".

String Comment

The description of the cookie. This description is displayed when the browser displays cookie information.

int version

The version number used by the cookie. 0 indicates compliance with the cookie specification of Netscape and 1 represents the RFC 2019 specification of the following.

1.5.1 The validity period of a cookie

The maxage of a cookie determines the duration of the cookie, in seconds (Second). The Getmaxage () method and the Setmaxage (Intmaxage) method are used by the cookie to read and write the MaxAge property.

If the MaxAge property is positive, it means that the cookie will automatically expire after maxage seconds. The browser persists the cookie maxage as a positive number, which is written to the corresponding cookie file. The cookie remains in effect when the user logs on to the site, regardless of whether the client closes the browser or the computer, as long as it is maxage seconds.

The cookie information in the following code will be permanently valid.

Cookiecookie = new Cookie ("username", Urlencoder. Encode("Mei", "UTF-8"));

Cookie.setmaxage (Integer. Max_value);

Response.addcookie (cookie);

If MaxAge is negative, it means that the cookie is valid only in this browser window and in a subwindow that is open in this window, and the cookie is invalidated after the window is closed. MaxAge is a negative cookie, which is a temporary cookie that is not persisted and is not written to a cookie file. Cookie information is saved in the browser memory, so the cookie disappears when you close the browser.

The default MaxAge value for cookies 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 realized by setting the cookie to expire immediately. Expired cookies are deleted by the browser from the cookie file or in memory.

The response object provides a cookie action method with only one add action (cookie cookie). To modify a cookie, you can only use a cookie of the same name to overwrite the original cookie for the purpose of the modification. You only need to change the maxage to 0 when you delete it.

1.5.2 modification and deletion of cookies

Cookies do not provide modifications or deletions. 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.

If you want to delete a cookie, simply create a new cookie with the same name and set MaxAge to 0 and add it to response to overwrite the original cookie.

1.6 Permanent Login

If the user is on their own home computer on the Internet, log in to remember his login information, the next visit does not need to log in again, direct access. The way to do this is to keep the login information such as account number, password, etc. in the cookie, and control the validity of the cookie, and then verify the login information in the cookie on the next visit.

There are several scenarios for saving login information. The most direct is to keep the user name and password in the cookie, the next visit to check the cookie user name and password, compared with the database. This is a more dangerous option and generally does not store important information such as passwords in cookies.

Another option is to encrypt the password and save it to the cookie, which is decrypted on the next visit and compared to the database. This scheme is slightly safer. If you do not want to save the password, you can also save the time stamp of the login to the cookie and the database, only to verify the user name and logon timestamp.

These scenarios verify that the database is queried when validating the account. There is a scenario where the database is queried only once at logon, and the database is no longer queried for subsequent access to the authentication login information. The way to do this is to encrypt the account according to certain rules, and save it to the cookie together with the account number. The next time you visit, you only need to determine whether the encryption rules are correct.

2. Session

Session is a server-side use of the mechanism to record client status, the use of more than a cookie is simpler, the corresponding increase the storage pressure of the server.

2.1 Session Definition

The session is another mechanism for recording client status, but the cookie is stored in the client browser and the session is stored on the server. When the client browser accesses the server, the server logs the client information to the server in some way. This is the session. When the client browser accesses it again, it only needs to query the client's status from that session.

If the cookie mechanism is to determine the customer's identity by checking the "pass" on the client, then the session mechanism verifies the customer's identity by checking the "customer schedule" on the server. Session is equivalent to a program on the server set up a customer profile, when customers visit only need to query the customer file table on it.

Basic use of the 2.2 session in Java EE

The class corresponding to the session is the Javax.servlet.http.HttpSession class. Each visitor corresponds to a Session object, and all of the client's status information is stored in the session object. The session object is created the first time the client requests the server. The session is also a Key-value property pair that reads and writes client state information through the getattribute (string key) and setattribute (string Key,object value) methods. The session,request of the client obtained through the Request.getsession () method in the servlet can also use the GetSession (Boolean create) to get the session. The difference is that if the client's session does not exist, the Request.getsession () method returns NULL, and GetSession (TRUE) creates the session before returning the session.

The servlet must use request to programmatically get the HttpSession object, and the JSP has a built-in session object that can be used directly. If you use the <%@ page session= "false"%>, the Session object is unavailable.

2.2.1 Get session on server side

Httpsessionsession = Request.getsession ();

Stringusername = (String) session.getattribute ("username");

2.2.2 Setting session on server side

Httpsessionsession = Request.getsession ();

Session.setattribute ("username", "sa");

The life cycle of the 2.3 session

Session is saved on the server side. In order to obtain higher access speed, the server usually puts the session in memory. Each user will have a separate session. If the session content is too complex, a large number of clients accessing the server can cause memory overflow. Therefore, the information in the session should be as concise as possible.

Session is created automatically when the user accesses the server for the first time. It should be noted that only access to the JSP, servlet and other programs will be created session, only the HTML, image and other static resources do not create session. If the session has not been generated, you can also use Request.getsession (true) to force the session to be generated.

After the session is generated, the server updates the last access time of the session and maintains the session as long as the user continues to access it. Each time a user accesses a server, the server considers the user's session "active" once, regardless of whether the session is read or written.

Validity period of 2.4 session

As more and more users access the server, the session will be more and more. To prevent memory overflow, the server removes the session from memory that has not been active for a long period of time. This is the time-out period of the session. If you have exceeded the time-out period and have not accessed the server, the session will automatically expire.

The timeout period for the session is Maxinactiveinternal property, which can be obtained through the corresponding Getmaxinactiveinterval () and modified by Setmaxinactiveinterval (long interval).

The timeout period of the session can also be modified in Web. Xml. In addition, by invoking the invalidate () method of the session, the session can be invalidated.

2.5 Session requirements for the browser

Although the session is saved on the server and is transparent to the client, it still needs the support of the client browser for its normal operation. This is because the session needs to use a cookie as the identification mark. The HTTP protocol is stateless, and the session cannot determine whether it is the same client based on an HTTP connection, so the server sends a cookie named Jsessionid to the client browser whose value is the ID of the session (Httpsession.getid ( return value). The session is based on the cookie to identify whether it is the same user.

The cookie is automatically generated by 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, and the browser is disabled. Therefore, when the server is accessed by two browser windows of the same machine, two different sessions are generated. However, new windows that are opened by links, scripts, and so on in the browser window (that is, not by double-clicking on Windows that are open by desktop browser icons). This type of child window will share the parent window's cookie. Therefore, a session is shared.

Note : The newly opened browser window will generate a new session, except for the child window. The child window will share the session of the parent window.

What if the client browser disables the cookie feature or does not support cookies? The Java Web provides a solution: URL-Address rewriting.

2.6 URL Address rewriting

URL address Rewriting is a solution that does not support cookies for clients. 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 parse the rewritten 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 Encodeurl (StringUrl) Implementation of URL address rewriting, for example:

<a href= "<%= response.encodeurl (" Index.jsp?c=1&wd=java ")%>" >



This method automatically determines whether the client supports cookies. If the client supports cookies, the URL is output intact. If the client does not support cookies, the ID of the session is rewritten into the URL. The rewritten output might be something like this:

<a href= "Index.jsp;jsessionid=0ccd096e7f8d97b0be608afdc3e1931e?c=1&wd=java" >



That is, after the file name, the string "; Jsessionid=xxx" is added before the URL parameter. where XXX is the ID of the session. When the user clicks the link, it submits the session ID to the server via the URL, and the server obtains the session ID by resolving the URL address.

In the case of page redirection (redirection), the URL address rewrite can write:

Response.sendredirect (Response.encoderedirecturl ("administrator.jsp"));

The effect is the same as Response.encodeurl (string URL): If the client supports cookies, generates the original URL address, and if the cookie is not supported, returns the rewritten address with the Jsessionid string.

Note : Tomcat determines whether the client browser supports cookies based on whether the request contains cookies, although the client may support cookies, However, since the first request will not carry any cookies (because there is no cookie to carry), the URL address will still be rewritten after the address with Jsessionid. The server has already written a cookie in the browser when the second visit is made, so the address in the URL address rewrite will not be jsessionid.

3. Session and Cookie Comparison

3.1 Comparison from the access mode

Only ASCII strings can be saved in a cookie, and if you need to access Unicode characters or binary data, you need to encode UTF-8, GBK, or BASE64. Cookies also do not directly access Java objects, and it is difficult to use cookies to store slightly more complex information.

In the session, you can access any type of data, including string, Integer, List, map, and so on. The session can also be directly saved JavaBean and any Java object, etc., it is very convenient to use, can be seen as a Java container class.

3.2 Comparison from privacy security

Cookies are stored in the client browser and are visible to the client, and some programs on the client may snoop, copy, or even modify the contents of the cookie. The session is stored on the server, transparent to the client, and there is no risk of a sensitive information leak.

If the use of cookies, the better way is that sensitive information such as account password, such as try not to write to the cookie, it is best to encrypt the cookie information, submitted to the server and then decrypted.

3.3 Comparison from the validity period

Using cookies is a good choice to achieve long-lasting records of the user's login information. Just set the MaxAge property of the cookie to a very large data word or integer.max_value. The MaxAge property of the cookie supports this effect.

This effect can also be achieved theoretically using the session. Just call the method Setmaxinactiveinterval (Integer.max_value). However, since the session relies on a cookie named Jsessionid, and the cookie Jsessionid the maxage default is-1, the session will be disabled when the browser is closed, so the session does not achieve the effect of permanent information. Using URL-Address rewriting is also not possible.

And if you set the session time-out too long, the server will accumulate more sessions, the more likely to cause memory overflow.

3.4 Comparison from the burden on the server

The session is saved on the server side, and each user will have a session. If the number of concurrent access users is very large, it will generate a lot of sessions, consuming a lot of memory.

The cookie is stored on the client and does not occupy server resources. If the number of concurrent browsing users is very great, the cookie is a good choice.

3.5 Comparison from browser support

Cookies are supported by the client browser. If a customer disables cookies or does not support cookies, session tracking is invalidated.

If the client browser does not support cookies, you need to use session and URL rewrite. It is important to note that all session program URLs are URL-rewritten using Response.encodeurl (string url) or Response.encoderedirecturl (string url). Failure to do so causes session sessions to be tracked.

If the client supports cookies, the cookie can either be set to the browser container and the Subwindow is valid (set MaxAge to-1) or be valid in all browser windows (set MaxAge to an integer greater than 0). However, the session can only be valid in this browser window and in its child windows. If two browser windows are irrelevant, they will use two different sessions.

3.6 Comparing from cross-domain

Cookies support cross-domain access, such as setting the Domain property to ".", and all domain names that are suffixed with it can access the cookie. The session does not support cross-domain access and is valid only within the domain name in which it resides.

9.1   Requirements for session tracking HTTP is a stateless protocol: the State of the protocol means that the next transmission can "remember" the ability to transmit information, stateless refers to the same session (note what is called the same session) two consecutive requests do not understand each other, when the browser sends the request to the server, the server responds, But when the same browser sends a request to the server, he responds, but he doesn't know you're the browser, and every request and response is relatively independent. After the advent of Web applications in which clients interact dynamically with the server, HTTP stateless features are a serious impediment to the implementation of these applications, after all, the interaction needs to be followed, and the simple shopping cart program knows exactly what the user has chosen before. As a result, two techniques for keeping the HTTP connection state are created, one is a cookie, and the other is a solution where the session cookie is kept state by the client. By definition, a cookie is a special message sent to the client by the server, which is stored as a text file on the client, and then each time the client sends a request to the server, the special information is taken, and the technology is implemented with a cookie. After receiving a request from the client browser, the server is able to generate the client-specific information by analyzing the cookie stored in the request header, which dynamically generates the content corresponding to that client. A solution that is relative to a cookie is the session, which is maintained by the server. The meaning of the session needs to be clarified here. First, we usually translate sessions into conversations, so we can refer to a series of interactions between the client browser and the server as a session. From this semantics, we will refer to the duration of the session, what is done during the session and so on, and second, the session refers to the server side for the client to open up the storage space, in which the information is used to hold the state.        From this semantics, we will refer to what is stored in the session, how to get the matching content from the session according to the key value. To use the session, the first step is of course to create a session. So when is the session created? Of course, it is created in the process of running the server-side program, the different language implementation of the application has different methods to create the session, and in Java by calling HttpServletRequest's GetSession method (using True as a parameter) created. While the session is created, the server generates a unique session ID for the session, which is used in subsequent requests to regain theAfter the session is created, the session-related method can be called to add content to the session, which is only stored in the server, only the session ID sent to the client, and when the client sends the request again, This session ID will be taken, the server accepts the request will be based on the session ID to find the corresponding session, thereby re-use it. Formally, the state of the user is maintained.        The content of the session is also more, in the future post, I will continue to tell. In summary, HTTP itself is a stateless connection protocol, in order to support the interaction between the client and server, we need to use different technologies for the interactive storage state, and these different technologies are the cookie and session.

Session Tracker 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.