码迷,mamicode.com
首页 > Web开发 > 详细

Web专题二:Cookie与Session

时间:2020-05-11 22:01:57      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:响应   时间   serial   container   user   path   例子   ons   body   

Web专题二:Cookie与Session

http://www.rfc-editor.org/rfc/rfc6265.txt

HTTP是一种无状态协议,Cookie的出现正好解决了这种问题,Cookie是一种用来保存状态的机制,描述了从服务器发送状态信息给user agent(一般是浏览器)和从user agent返回状态信息给服务器的过程

User-Agent:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36

1.1.1. Cookie过程

服务器在HTTP响应response时携带 Set-Cookie头部,返回给user agent,并保存在user agent中,在后面的HTTP请求request头部可以携带Cookie头部,Cookie的信息来自于前面user agent收到的 Set-Cookie
例如:我们想发送一个 "session identifier"给user agent

   == Server -> User Agent ==

   Set-Cookie: SID=31d4d96e407aad42

   == User Agent -> Server ==

   Cookie: SID=31d4d96e407aad42

当然也可以携带多个Cookie

   == Server -> User Agent ==

   Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnly
   Set-Cookie: lang=en-US; Path=/; Domain=example.com

   == User Agent -> Server ==

   Cookie: SID=31d4d96e407aad42; lang=en-US

1.1.2. Cookie语法

每个Cookie都是以name-value对的方式开头,中间以; 分隔,后面跟着零个或多个的attribute-value对

  • response
       Set-Cookie: cookie-name=cookie-value; attribute=value
       Set-Cookie: cookie-name-1=cookie-value-1; attribute-1=value-1
       ...
       Set-Cookie: cookie-name-n=cookie-value-n; attribute-n=value-n
    
  • request
       Set-Cookie: cookie-name=cookie-value; [cookie-name-1=cookie-value-1; ... cookie-name-n=cookie-value-n]
    

1.1.3. Cookie属性

属性 说明 例子
Expires 用日期、时间表示cookie生存最大的生命周期 Expires=Sun, 06 Nov 1994 08:49:37 GMT
Max-Age 用秒数表示cookie生存最大的生命周期,比Expires的优先级更高 Max-Age=65535
Domain 表示cookie可以被发送到哪些主机 Domain=example.com
Path 表示cookie的作用域,没有指定时缺省值是request-uri的路径 Path=/
Secure 表示cookie使用安全频道如TSL发送 Secure
HttpOnly 限定cookie只用于HTTP请求,不用于非HTTP的API,如把web浏览器中cookie暴露出来的脚本 HttpOnly

javax.servlet.http.Cookie就包含了这些属性

// javax.servlet.http.Cookie

public class Cookie implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private final String name;
    private String value;
    private int version = 0;
    private String comment;
    private String domain;
    private int maxAge = -1;
    private String path;
    private boolean secure;
    private boolean httpOnly;
}

2.1. session

Session保存在服务端的一种数据,用来跟踪用户的会话状态,默认保存在服务器的一个文件中

实现方式主要有下面几种:

  • Cookie实现:

将session-id保存在Cookie中,如:Set-Cookie: SID=31d4d96e407aad42,在第一次请求服务器将session-id放入Cookie中返回给user agent,后续user agent发送请求服务器就能从session-id中知道是哪个用户在操作

  • URL重写:

将session-id作为参数添加在url的后面

  • 表单隐藏:

提交表单时,将session-id作为一个隐藏字段,发送给服务器

Web专题二:Cookie与Session

标签:响应   时间   serial   container   user   path   例子   ons   body   

原文地址:https://www.cnblogs.com/myibu/p/12872083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!