Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cookie与Session有什么区别? #5

Open
CodeRookie262 opened this issue Dec 21, 2020 · 0 comments
Open

Cookie与Session有什么区别? #5

CodeRookie262 opened this issue Dec 21, 2020 · 0 comments

Comments

@CodeRookie262
Copy link
Owner

CodeRookie262 commented Dec 21, 2020

Cookie 和 Session 的诞生主要为了解决因为 http 是无状态的,导致同一站点下不能共享状态(例如登录状态)的问题。

当客户端发起http请求到服务端时,服务端接受到请求后会生成一个 Session 临时文件到服务端的内存中,并且会通过哈希函数生成一个唯一标识与之对应,就是 sessionId,然后发起一个http响应到客户端,并且会在响应头的Set-Cookie 携带这个唯一标识 sessionId ,客户端接收到响应头中 Set-Cookie 后会自动保存为 Cookie,待下次客户端发起请求时会在请求头中携带 Cookie 发送给服务端,服务端接收到请求后就会解析 Cookie,校验信息的 sessionId 准确性以及时效性后给客户端响应处理后的数据。

CookieSession的区别主要在于:

  1. Cookie 储存在客户端,而 Session储存在服务端中;
  2. Cookie 的安全性低于 Session,例如某些网站的登录状态是携带在Cookie中,如果我们拷贝一份Cookie粘贴到别的未登陆过浏览器后再访问这个站点时会处于登录状态;
  3. 因为 Session 是保存在服务器的内存中,如果访问数量过多会影响到服务器性能;
  4. 一个 Cookie 的最大保存容量为 4K,一个站点最多可以保存 20 个 Cookie,储存容量远小于 Session;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant