当前位置:网站首页>【web】理解 Cookie 和 Session 机制
【web】理解 Cookie 和 Session 机制
2022-08-02 02:14:00 【爱干饭的猿】
目录
3.1 HttpServletRequest 类中的相关方法
3.2 HttpServletResponse 类中的相关方法
【大家好,我是爱干饭的猿,如果喜欢这篇文章,点个赞,关注一下吧,后续会持续分享每日一题和SSM其他重要知识点总结】
上一篇文章:《【SSM】初识Spring & 存取Bean对象》
1. 理解Cookie
HTTP 协议自身是属于 “无状态” 协议的
“无状态” 的含义指的是:默认情况下 HTTP 协议的客户端和服务器之间的本次通信和下次同行没有直接联系
但是在实际开发中,我们很多时候都需要知道请求和请求间的关系,比如登录某个网站后,再次访问的时候服务器就能知道你是否已经登陆过了。

图中的 “令牌” 就存储在Cookie 字段中,“令牌”就类似于一张VIP 卡或通行证,当你有这张令牌后就能进行后续的访问了。
Cookie实际上是一小段的⽂本信息。客户端请求服务器,如果服务器需要记录该用户状态,就使⽤response向客户端浏览器颁发⼀个Cookie。客户端浏览器会把Cookie保存起来。当浏览器再请求该网站时,浏览器把请求的网址连同该Cookie⼀同提交给服务器。服务器检查该Cookie,以此来辨认⽤户状态。服务器还可以根据需要修改Cookie 的内容。
而此时在服务器这边就需要记录令牌信息,以及令牌对应的用户信息,这个就是Session 机制做的工作。
2. 理解会话机制(Session)
服务器在同一时间可能会收到许多请求,服务器要区分清楚每个请求的用户是谁,就需要在服务器记录每个用户的令牌和用户信息。
所有会话的本质是一个“哈希表”,存储一些键值对结构,key 就是令牌的 ID(token/sessionId), value 就是 用户信息。
sessionId 和 token 就可以理解成是同一个东西的不同叫法(不同视角的叫法)

- 当用户登陆的时候, 服务器在 Session 中新增一个新记录, 并把 sessionId / token 返回给客户端. (例 如通过 HTTP 响应中的 Set-Cookie 字段返回).
- 客户端后续再给服务器发送请求的时候, 需要在请求中带上 sessionId/ token. (例如通过 HTTP 请求 中的 Cookie 字段带上).
- 服务器收到请求之后, 根据请求中的 sessionId / token 在 Session 信息中获取到对应的用户信息, 再进行后续操作.
注意:Servlet 的Session 是保存在内存中,重启服务器Session 数据就会消失,相当于重新开始一个进程。
3. 核心方法
3.1 HttpServletRequest 类中的相关方法

3.2 HttpServletResponse 类中的相关方法

3.3 HttpSession 类中的相关方法
一个 HttpSession 对象里面包含多个键值对. 我们可以往 HttpSession 中存任何我们需要的信息.

3.4 Cookie 类中的相关方法
每个 Cookie 对象就是一个键值对.

- HTTP 的 Cooke 字段中存储的实际上是多组键值对. 每个键值对在 Servlet 中都对应了一个 Cookie 对象
- 通过 HttpServletRequest.getCookies() 获取到请求中的一系列 Cookie 键值对
- 通过 HttpServletResponse.addCookie() 可以向响应中添加新的 Cookie 键值对
a. 首次访问
@WebServlet("/first-visit")
public class FirstVisitServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // false 不会新增加柜子,ture 会新增柜子
HttpSession session = req.getSession(true);
// 记录
session.setAttribute("Date",new Date());
resp.setCharacterEncoding("utf-8");
resp.setContentType("txt/plain");
resp.getWriter().print("办理会员成功!");
}
}b. 首次访问后得到Cookie 就能发出带有Cookie 的请求
@WebServlet("/get-time")
public class GetCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("txt/plain");
PrintWriter writer = resp.getWriter();
// false 不会新增加柜子,ture 会新增柜子
HttpSession session = req.getSession(false);
if(session == null){
writer.println("没有柜子");
return;
}
Object o = session.getAttribute("Date");
if(o == null){
writer.println("有柜子但是会员信息为空");
return;
}
Date date = (Date) o;
writer.println("有会员,会员信息为:" + date);
}
}4. Cookie 和 Session 的区别
- Cookie 是客户端的机制,Session 是服务器端的机制.
- Cookie 和 Session 经常会在一起配合使用. 但是不是必须配合.
完全可以用 Cookie 来保存一些数据在客户端. 这些数据不一定是用户身份信息, 也不一定是 token / sessionId
Session 中的 token / sessionId 也不需要非得通过 Cookie / Set-Cookie 传递.
4.1 只存Cookie
@WebServlet("/only-set-cookie")
public class OnlySetCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie1 = new Cookie("name","xiao");
// Cookie 其它属性
// cookie1.setMaxAge(60); // 设置过期时间
// cookie1.setComment(); // 设置Cookie 注释
// cookie1.setDomain(); // 设置支持的域名,可以让支持根域名 域名增大范围
// cookie1.setPath(); // 设置支持的路径 路径缩小范围,一般默认为"/",根目录下都带Cookie
// // 其它
resp.addCookie(cookie1);
Cookie cookie2 = new Cookie("gender","male");
resp.addCookie(cookie2);
}
}4.2 只取Cookie
@WebServlet("/only-get-cookie")
public class OnlyGetCookie extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() +" => "+cookie.getValue());
}
}
}本次分享就到这里,如果你喜欢这篇文章,请点赞加关注吧,或者如果你对文章有什么困惑,可以私信我。
边栏推荐
- ¶Backtop 回到顶部 不生效
- 手写一个博客平台~第一天
- Speed up your programs with bitwise operations
- 优炫数据库导库导错了能恢复吗?
- The first time I wrote a programming interview question for Niu Ke: input a string and return the letter with the most occurrences of the string
- Centos7 安装postgresql并开启远程访问
- Handwriting a blogging platform ~ the first day
- Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion
- 【Unity入门计划】2D Game Kit:初步了解2D游戏组成
- Win Go开发包安装配置、GoLand配置
猜你喜欢

2022-08-01 mysql/stoonedb慢SQL-Q18分析

Chengdu openGauss user group recruit!
![[ORB_SLAM2] void Frame::ComputeImageBounds(const cv::Mat & imLeft)](/img/ed/ffced88c9d23c20ccf380494051381.jpg)
[ORB_SLAM2] void Frame::ComputeImageBounds(const cv::Mat & imLeft)

"NetEase Internship" Weekly Diary (1)

Typescript31 - any type

拼多多借力消博会推动国内农产品品牌升级 看齐国际精品农货

The failure to create a role in Dahua Westward Journey has been solved

手写博客平台~第二天

LeetCode Brushing Diary: 74. Searching 2D Matrix

Speed up your programs with bitwise operations
随机推荐
LeetCode Brushing Diary: 74. Searching 2D Matrix
Effects of Scraping and Aggregation
Typescript31 - any type
Analysis of volatile principle
【Unity入门计划】2D Game Kit:初步了解2D游戏组成
The characteristics and principle of typescript29 - enumeration type
ALCCIKERS Shane 20191114
oracle query scan full table and walk index
LeetCode刷题日记:34、 在排序数组中查找元素的第一个和最后一个位置
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation
PHP uses PHPRedis and Predis
Rasa 3.x 学习系列- Rasa - Issues 4873 dispatcher.utter_message 学习笔记
Simple example of libcurl accessing url saved as file
C language inserted into the characters of simple exercises
拼多多借力消博会推动国内农产品品牌升级 看齐国际精品农货
LeetCode刷题日记: 33、搜索旋转排序数组
LeetCode刷题日记:53、最大子数组和
The failure to create a role in Dahua Westward Journey has been solved
Data transfer at the data link layer
【ORB_SLAM2】void Frame::AssignFeaturesToGrid()