Detailed Cookie Mechanism

1 What are cookies?

Cookie means "sweet cookie", which is a mechanism proposed by the W3C organization and first developed by the Netscape community. At present, cookies have become a standard, and all major browsers such as IE, Netscape, Firefox, Opera, etc. support cookies.

Since HTTP is a stateless protocol, the server has no way of knowing the identity of the client from the network connection alone. How to do it? Just issue a pass to the clients, one for each person, and whoever visits must bring their own pass. This allows the server to verify the client's identity from the passport. This is how cookies work .

 

2 How are cookies used?

Cookie is encapsulated into javax.servlet.http.Cookie class in Java. Each cookie is an object of that Cookie class. The server operates on client cookies by manipulating Cookie class objects. Obtain all cookies submitted by the client through request.getCookie() (returned in the form of Cookie[] array), and set cookies to the client through response.addCookie(Cookiecookie).

 

The cookie object saves the user state in the form of key-value attribute pairs. One cookie object saves one attribute pair, and one request or response uses multiple cookies at the same time.

 

3 The non-cross-domain nature of cookies

Many websites use cookies. For example, Google issues cookies to clients and Baidu issues cookies to clients. Will the browser also carry the cookie issued by Baidu when visiting Google? Or can Google modify the cookies issued by Baidu?

the answer is negative. Cookies are not cross-domain .

 

4.Unicode encoding: save Chinese

Chinese is different from English characters. Chinese belongs to Unicode characters and occupies 4 characters in memory, while English belongs to ASCII characters and occupies only 2 bytes in memory . When using Unicode characters in cookies, it is necessary to encode Unicode characters, otherwise the characters will be garbled.

Tip: Chinese can only be encoded in cookies. Generally use UTF-8 encoding. It is not recommended to use Chinese encoding such as GBK, because the browser does not necessarily support it, and JavaScript does not support GBK encoding.

 

 

5 Set the properties of the cookie

In addition to name and value, cookies also have several other commonly used attributes. Each property corresponds to a getter method and a setter method. All properties of the Cookie class are shown in Table 1.1.

Table 1.1 Common Cookie Attributes

property name

Depiction

String name

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

Object value

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

int maxAge

The expiration time of the cookie, in seconds. If positive, the cookie expires after maxAge seconds. If it is a negative number, the cookie is a temporary cookie, which will be invalid after closing the browser, and the browser will not save the cookie in any form. If it is 0, it means to delete the cookie. Defaults to –1

boolean secure

Whether the cookie is only transmitted using a secure protocol. Security Protocol. Security protocols include HTTPS, SSL, etc., which encrypt data before transmitting it on the network. Default is false

String path

The usage path of this cookie. If set to "/sessionWeb/", only programs whose contextPath is "/sessionWeb" can access the cookie. If it is set to "/", the contextPath under this domain name can access the cookie. Note that the last character must be "/"

String domain

可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”

String comment

该Cookie的用处说明。浏览器显示Cookie信息的时候显示该说明

int version

 

6  Cookie的有效期

Cookie的maxAge决定着Cookie的有效期,单位为秒(Second)。Cookie中通过getMaxAge()方法与setMaxAge(int maxAge)方法来读写maxAge属性。

如果maxAge属性为正数,则表示该Cookie会在maxAge秒之后自动失效。浏览器会将maxAge为正数的Cookie持久化,即写到对应的Cookie文件中。无论客户关闭了浏览器还是电脑,只要还在maxAge秒之前,登录网站时该Cookie仍然有效。下面代码中的Cookie信息将永远有效。

 

eg:

Cookie cookie = new Cookie("username","helloweenvsfei");   // 新建Cookie

cookie.setMaxAge(Integer.MAX_VALUE);           // 设置生命周期为MAX_VALUE

response.addCookie(cookie);                    // 输出到客户端

 

7  Cookie的修改、删除

Cookie并不提供修改、删除操作。如果要修改某个Cookie,只需要新建一个同名的Cookie,添加到response中覆盖原来的Cookie。

如果要删除某个Cookie,只需要新建一个同名的Cookie,并将maxAge设置为0,并添加到response中覆盖原来的Cookie。注意是0而不是负数。负数代表其他的意义。读者可以通过上例的程序进行验证,设置不同的属性。

注意:修改、删除Cookie时,新建的Cookie除value、maxAge之外的所有属性,例如name、path、domain等,都要与原Cookie完全一样。否则,浏览器将视为两个不同的Cookie不予覆盖,导致修改、删除失败。

 

 

8  Cookie的域名

Cookie是不可跨域名的。域名www.google.com颁发的Cookie不会被提交到域名www.baidu.com去。这是由Cookie的隐私安全机制决定的。隐私安全机制能够禁止网站非法获取其他网站的Cookie。

正常情况下,同一个一级域名下的两个二级域名如www.helloweenvsfei.com和images.helloweenvsfei.com也不能交互使用Cookie,因为二者的域名并不严格相同。如果想所有helloweenvsfei.com名下的二级域名都可以使用该Cookie,需要设置Cookie的domain参数,例如:

Cookie cookie = new Cookie("time","20080808"); // 新建Cookie

cookie.setDomain(".helloweenvsfei.com");           // 设置域名

cookie.setPath("/");                              // 设置路径

cookie.setMaxAge(Integer.MAX_VALUE);               // 设置有效期

response.addCookie(cookie);                       // 输出到客户端

 

读者可以修改本机C:\WINDOWS\system32\drivers\etc下的hosts文件来配置多个临时域名,然后使用setCookie.jsp程序来设置跨域名Cookie验证domain属性。

注意:domain参数必须以点(".")开始。另外,name相同但domain不同的两个Cookie是两个不同的Cookie。如果想要两个域名完全不同的网站共有Cookie,可以生成两个Cookie,domain属性分别为两个域名,输出到客户端。

 

9  Cookie的路径

domain属性决定运行访问Cookie的域名,而path属性决定允许访问Cookie的路径(ContextPath)。例如,如果只允许/sessionWeb/下的程序使用Cookie,可以这么写:

Cookie cookie = new Cookie("time","20080808");     // 新建Cookie

cookie.setPath("/session/");                          // 设置路径

response.addCookie(cookie);                           // 输出到客户端

设置为“/”时允许所有路径使用Cookie。path属性需要使用符号“/”结尾。name相同但domain相同的两个Cookie也是两个不同的Cookie。

 

注意:页面只能获取它属于的Path的Cookie。例如/session/test/a.jsp不能获取到路径为/session/abc/的Cookie。使用时一定要注意。

 

10  Cookie的安全属性

HTTP协议不仅是无状态的,而且是不安全的。使用HTTP协议的数据不经过任何加密就直接在网络上传播,有被截获的可能。使用HTTP协议传输很机密的内容是一种隐患。如果不希望Cookie在HTTP等非安全协议中传输,可以设置Cookie的secure属性为true。浏览器只会在HTTPS和SSL等安全协议中传输此类Cookie。下面的代码设置secure属性为true:

eg:

Cookie cookie = new Cookie("time", "20080808"); // 新建Cookie

cookie.setSecure(true);                           // 设置安全属性

response.addCookie(cookie);                        // 输出到客户端

 

提示:secure属性并不能对Cookie内容加密,因而不能保证绝对的安全性。如果需要高安全性,需要在程序中对Cookie内容加密、解密,以防泄密。

 

11  JavaScript操作Cookie

Cookie是保存在浏览器端的,因此浏览器具有操作Cookie的先决条件。浏览器可以使用脚本程序如JavaScript或者VBScript等操作Cookie。这里以JavaScript为例介绍常用的Cookie操作。例如下面的代码会输出本页面所有的Cookie。

<script>document.write(document.cookie);</script>

由于JavaScript能够任意地读写Cookie,有些好事者便想使用JavaScript程序去窥探用户在其他网站的Cookie。不过这是徒劳的,W3C组织早就意识到JavaScript对Cookie的读写所带来的安全隐患并加以防备了,W3C标准的浏览器会阻止JavaScript读写任何不属于自己网站的Cookie。换句话说,A网站的JavaScript程序读写B网站的Cookie不会有任何结果。

 

 

参考:http://blog.csdn.net/fangaoxin/article/details/6952954/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326232743&siteId=291194637