Cookie和Session有什么区别?

They are both used to store information.

cookies: they are stored in the client computer. for example: the name, address that can be automatically filled in a form of a site.
sessions: they are be stored both in client side and in the server side. a session ends when the user close the browser or leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

不同点在于:
①在存储方面:Cookie保存在客户端浏览器中,而Session保存在服务器上。Cookie中只能保管ASCII字符串,而Session中能够存取任何类型的数据。
②在生命周期方面:cookie是通过maxAge设置过期时间。若设置了过期时间,浏览器就会把cookie保存到硬盘上,关闭后再次打开浏览器,这些cookie仍然有效直到超过设定的过期时间。Session在用户第一次访问服务器的时候自动创建。Session生成后, 只要用户继续访问,服务器就会更新Session的最后访问时间,并维护该Session。(有点类似缓存控制算法LRU) 为防止内存溢出,服务器会把长时间内没有活跃的Session从内存删除。这个时间就是Session的超时时间。如果超过了超时时间没访问过服务器,Session就自动失效了。
③依赖方面:Session保存在服务器,对客户端是透明的,它的正常运行仍然需要客户端浏览器的支持。并且在识别是否是同一浏览器方面:服务器向客户端浏览器发送一个名为JSESSIONID的Cookie,Session依据该Cookie来识别是否为同一用户。
④隐私策略方面:Cookie存储在客户端阅读器中,对客户端是可见的,客户端的一些程序可能会窥探、复制以至修正Cookie中的内容。而Session存储在服务器上,对客户端是透明的,不存在敏感信息泄露的风险。

各自的优缺点:
Cookie的优点在于:他有很高的可拓展性和可用性,不需要大量服务器资源,因为cookie储存在客户端。
Seesion的优点在于:其易于读写,比较安全。
Cookie的缺点在于:cookie的数量和长度每个域名都是有限制的,20条cookie,且单个长度不能超过4k, cookie的可能会被客户端的一些恶意程序篡改。
Session的缺点在于:如果浏览器被设置为不兼容cookie,那么该用户就无法使用seesion这个变量。而且seesion会在一段时间内保存在服务器上,当访问增多的时候,会占用较大的服务器性能。

posted @ 2020-11-01 03:06  EvanMeetTheWorld  阅读(22)  评论(0)    收藏  举报