2. Session Tracking Technology

Source: Internet
Author: User
Tags http cookie send cookies

1. What is session tracking technology?

We need to know what a conversation is! The session can be understood as a meeting between the client and the server, which may contain multiple requests and responses in a single meeting. For example, you give 10086 call, you are the client, and 10086 service personnel is the server. From the moment the two sides are connected, the conversation begins, and a call to one side indicates that the session is over. During a call, you make multiple requests to 10086, and the multiple requests are in one session.

In Javaweb, the client starts the first request to a server, and the session begins until the client closes the browser session.

Sharing data in multiple requests for one session is the session tracking technology. For example, in a session the request is as follows:

    • Request Bank homepage;
    • Request Login (request parameter is user name and password);
    • Request for transfer (request parameters related to the transfer of data);
    • Request Credit Card repayment (request parameters related to repayment of data).

In this session, the current user information must be shared in this session, because the login is Zhang San, then the transfer and repayment must be relatively Zhang San transfer and repayment! This means that we have the ability to share data during a session.

We know that the HTTP protocol is a stateless protocol, which means that each request is independent! The status of the previous request cannot be logged. But the HTTP protocol can use cookies to complete session tracking!

In Javaweb, sessions are used to complete session tracking, which relies on cookie technology.

2.Cookie Overview

2.1 What is a cookie?

Cookies translated into Chinese are small desserts, cookies mean. In HTTP it represents a small dessert that the server sends to the client browser. In fact, a cookie is a key and a value that is sent to the client browser as the server-side response. The client browser then saves the cookie and sends the cookie back to the server the next time it accesses the server.

A cookie is a key-value pair that is created by the server and then sent to the client by a response. The client saves the cookie and marks the source of the cookie (which server's cookie). When a client makes a request to the server, it sends all of this server cookie to the server in the request, so the server can identify the client!

2.2 Cookie Specification

    1. Maximum cookie size is 4KB;
    2. A server holds up to 20 cookies on the client browser;
    3. A maximum of 300 cookies are saved in a browser;

The above data is only the HTTP cookie specification, but in the browser war today, some browsers in order to defeat the opponent, in order to demonstrate their ability, the cookie specification may be "extended", for example, each cookie size of 8KB, up to 500 cookies can be saved! But there is no possibility of taking your hard drive full!

Note that cookies are not shared between different browsers. In other words, when you use IE to access the server, the server will send a cookie to IE, and then saved by IE, when you use Firefox to access the server, it is not possible to put IE saved cookies sent to the server.

2.3 Cookies and HTTP headers

Cookies are passed through the HTTP request and response headers on the client and server side:

Cookie: The request header, the client sends to the server side;

    • Format: cookie:a=a; B=b; C=c. That is, multiple cookies are separated by semicolons;

Set-cookie: Response header, server-side sent to the client;

    • A Cookie object a Set-cookie:

Set-cookie:a=a

Set-cookie:b=b

Set-cookie:c=c

2.4 Cookie Coverage

If the server sends a duplicate cookie, it overwrites the original cookie, such as the cookie sent by the client's first request server: Set-cookie:a=a; the second request server-side sends: SET-COOKIE:A=AA, Then the client leaves only one cookie, namely: A=aa.

2.5 Cookie First Example

In our case, the client Access Aservlet,aservlet adds a cookie to the response, and the browser automatically saves the cookie. The client then accesses Bservlet, and the browser automatically prints the cookie in the request with the Cookie,bservlet request.

Aservlet

 PackageCn.itcast.servlet;Importjava.io.IOException;ImportJava.util.UUID;Importjavax.servlet.ServletException;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Send cookies to clients *@authorAdministrator **/ Public classAservletextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8"); String ID= Uuid.randomuuid (). toString ();//generate a random stringCookie cookie =NewCookie ("id", id);//Create Cookie object, specify first name and valueResponse.addcookie (cookie);//Add a cookie object to the responseResponse.getwriter (). Print ("The ID has been sent to you"); }}

Bservlet

 PackageCn.itcast.servlet;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** Get the cookie in the client request *@authorAdministrator **/ Public classBservletextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8"); Cookie[] CS= Request.getcookies ();//get the cookie in the request        if(cs! =NULL) {//If a cookie exists in the request             for(Cookie C:cs) {//Traverse All Cookies                if(C.getname (). Equals ("id")) {//Gets the cookie name if the cookie name is IDResponse.getwriter (). Print ("Your ID is:" + c.getvalue ());//Print Cookie Value                }            }        }    }}

2.6 The Life of cookies

Sending cookies, using Response.addcookie (cookies)

Get cookies, use cookie[] request.getcookies ()

Cookie life: How long a cookie can survive on the client

    • Greater than 0: what is the value, then how many seconds
    • equals 0: Delete the cookie immediately
    • Less than 0 (default): Only live in browser memory.

2.6.1 What is the life of a cookie

Cookies are more than just name and Value,cookie or life. The so-called life is the time at which the cookie is valid at the client and can be set by setmaxage (int).

    • Cookie.setmaxage ( -1): The default value of the MaxAge property of a cookie is-1, which means that it only survives in browser memory . Once you close the browser window, the cookie disappears.
    • Cookie.setmaxage (60*60): Indicates that the cookie object can survive for 1 hours. When the life is greater than 0 o'clock, the browser will save the cookie to the hard disk, even if you close the browser, even if you restart the client computer, the cookie will survive 1 hours;
    • Cookie.setmaxage (0): Cookie life equals 0 is a special value, it means that the cookie is voided! In other words, if the original browser has saved this cookie, you can delete the cookie by Setmaxage (0) of the cookie. This cookie is deleted either in the browser memory or on the client's hard disk.

Path of 3.Cookie

Do you always have to return cookies? Use the path of the cookie to control whether or not to return cookies to the server!

L when there is no path to the cookie: the path of the current resource is a cookie!

    • For example:/day11_3/aservlet, the Aservlet response cookie has a path of/day11_3 when no path is set;
    • For example:/day11_3/servlet/aservlet, then the Aservlet response cookie has a path of/day11_3/servlet when no path is set.

• Do I have to return cookies when accessing server resources? If the resource path that is accessed contains a cookie path, it is returned, otherwise it is not returned.

    • For example, the path to access is Http://localhost:8080/day11_3/CServlet

Each cookie has its own path!!! The path is related to whether to return cookies!!!

The default path of the cookie (when no path is set), which is the path of the current servlet!!!

http://localhost:8080/day11_3/servlet/bservlet

3.1 What is the path of a cookie

There is now web App A, which sends 10 cookies to the client, which means that the client will include these 10 cookies in the request regardless of which servlet accesses app a! But perhaps only aservlet needs to read the cookie in the request, while the other servlet simply does not get the cookie in the request. This means that the client browser sometimes sends these cookies as superfluous!

You can specify the browser by setting the path of the cookie, and what kind of cookie is included when accessing what path.

3.2 The relationship between the cookie path and the request path

Let's look at the role of the cookie path:

The following is the path of the 3 cookies saved by the client browser:

A:/cookietest;

B:/cookietest/servlet;

C:/cookietest/jsp;

Here is the URL of the browser request:

A:http://localhost:8080/cookietest/aservlet;

B:http://localhost:8080/cookietest/servlet/bservlet;

C:http://localhost:8080/cookietest/jsp/cservlet;

l When requesting a, a is included in the request;

l when request B, will include a, b in the request;

L request C, will include a, c in the request;

That is, if the request path contains a cookie path, the cookie is included in the request, otherwise it will not be included in the request.

L A requested URL contains "/CookieTest", so a cookie with the path "/CookieTest" will be included in the request;

The URL requested by L B contains "/CookieTest" and "/cookietest/servlet", so the request contains two cookies with the path "/CookieTest" and "/cookietest/servlet";

The URL requested by L B contains "/CookieTest" and "/cookietest/jsp", so the request contains two cookies with the path "/CookieTest" and "/cookietest/jsp";

3.3 Setting the path of the cookie

The path to the cookie is set using the SetPath () method, for example:

Cookie.setpath ("/cookietest/servlet");

If the path to the cookie is not set, the default value of the cookie path currently accesses the path of the resource, for example:

L The default path for cookies added when accessing Http://localhost:8080/cookietest/AServlet is/cookietest;

L The default path for cookies added when accessing Http://localhost:8080/cookietest/servlet/BServlet is/cookietest/servlet;

L The default path for cookies added when accessing Http://localhost:8080/cookietest/jsp/BServlet is/cookietest/jsp;

The domain attribute of 4.Cookie (even if the site has a two-level domain sharing cookie)

Take Baidu as an example

Http://www.baidu.com

Http://zhidao.baidu.com

Http://news.baidu.com

Http://tieba.baidu.com

Now I want to share cookies between these hosts (for example, a cookie that responds in www.baidu.com, which can be included in a news.baidu.com request). Obviously, now is not the problem of the path, but the host problem, that is, the problem of the domain name. Dealing with this problem is really simple and requires only two steps:

L Set the cookie path to "/": C.setpath ("/");

L Set the cookie domain as ". Baidu.com":c.setdomain (". baidu.com ").

When domain is ". Baidu.com", cookies are shared regardless of the prefix. But now we need to set up two virtual hosts: Www.baidu.com and news.baidu.com.

5.Cookie Save Chinese

No Chinese can be saved in cookies! You need to convert Chinese to URL encoding before you can save it. This also means that after reading the cookie, you also use URL decoding!!!

The name and value of the cookie cannot be used in Chinese, and if you want to use Chinese in a cookie, you need to encode the Chinese URL first and then place the encoded string in the cookie.

Add a cookie to the client response

        String name = Urlencoder.encode ("name", "UTF-8");         = Urlencoder.encode ("Zhang San", "UTF-8");         New Cookie (name, value);        C.setmaxage (3600);        Response.addcookie (c);

Get a cookie from a client request

        Response.setcontenttype ("Text/html;charset=utf-8");         = request.getcookies ();         if NULL             {for(Cookie c:cs) {                = Urldecoder.decode (C.getname (), "UTF-8");                = Urldecoder.decode (C.getvalue (), "UTF-8");                 = name + ":" + value + "<br/>";                Response.getwriter (). print (s);            }        }

2. Session Tracking Technology

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.