Cookie 机制

1. Cookie

Web使用HTTP协议传输数据,而HTTP协议是无状态协议。(DNS则是有状态协议)

协议的状态是指下一次传输可以“记住”这次传输信息的能力,

为了保证服务器的内存,HTTP不会为了下一次连接而维护这次连接所传输的信息。这就是HTTP无状态协议。

Cookie的作用就是弥补这种无状态的不足。

通过储存在用户本地终端上的数据,服务器可以辨别用户身份、进行每个会话的跟踪。

在浏览器地址栏输入:

JavaScript: alert(document.cookie)

可以查看当前网站的cookie。

2. cookie的特性:

2.1. 每个特定的域名下最多生成50个cookie

2.2 可加密,安全传输技术,可降低被破解的风险

2.3 可设置有效期,这样被盗的可能只是过期的 cookie

2.4 有些状态无法保存在客户端。

2.5 不可跨域。比如访问Google不会读取、或者操作访问百度时保存的cookie。

3. 设置cookie的域名,同一个一级域名下的2级域名可互相访问cookie:

Cookie cookie = new Cookie("time","20170808"); // 新建Cookie
cookie.setDomain(".helloweenvsfei.com");           // 设置域名 
cookie.setPath("/");                              // 设置路径
cookie.setMaxAge(Integer.MAX_VALUE);               // 设置有效期
response.addCookie(cookie);                       // 输出到客户端

域名只能指定为当前域名或上级域名(包括上级的上级,等等),此外都是无效的。

An explicitly specified domain must always start with a dot. 域名的属性值必须以点开头。

4. Rejecting Cookies: 以下情况cookie会被拒绝

   To prevent possible security or privacy violations, a user agent
   rejects a cookie (shall not store its information) if any of the
   following is true:

   * The value for the Path attribute is not a prefix of the request-
     URI.

   * The value for the Domain attribute contains no embedded dots or
     does not start with a dot.
   域名属性的值不包含嵌入的点或不以点开头。
* The value for the request-host does not domain-match the Domain attribute. 域名和所要提交的http的host不同,那么对应的cookie则是无效的 * The request-host is a FQDN (not IP address) and has the form HD, where D is the value of the Domain attribute, and H is a string that contains one or more dots.
     请求的主机是一个正式域名(不是IP地址),啊这个form HD不知道怎么翻译,大概就是,H是request - host 字符串,包含一个或以上的点,D为Domain属性的值,
    但是可以直接查看官网的例子来理解这段话:
    请求的url为  y.x.foo.com 设置的domain为.foo.com,会被拒绝。
原文地址:https://www.cnblogs.com/dodocie/p/7307729.html