当前位置:网站首页>【web】Understanding Cookie and Session Mechanism
【web】Understanding Cookie and Session Mechanism
2022-08-02 02:17:00 【Ape who loves dry rice】
目录
3.1 HttpServletRequest 类中的相关方法
3.2 HttpServletResponse 类中的相关方法
【大家好,我是爱干饭的猿,如果喜欢这篇文章,点个赞,关注一下吧,The follow-up will continue to share the daily question and answerSSMSummary of other important knowledge points】
上一篇文章:《【SSM】初识Spring & 存取Bean对象》
1. 理解Cookie
HTTP 协议自身是属于 “无状态” 协议的
“无状态” 的含义指的是:默认情况下 HTTP The communication between the client and the server of the protocol has no direct connection with the next peer
但是在实际开发中,We often need to know the relationship between requests and requests,For example, after logging into a website,When you visit again, the server will know if you have already logged in.

图中的 “令牌” 就存储在Cookie 字段中,“令牌”Just like oneVIP card or pass,After you have this token, you can make subsequent accesses.
CookieActually a short paragraph⽂本信息.客户端请求服务器,如果服务器需要记录该用户状态,就使⽤responseIssued to client browsers⼀个Cookie.客户端浏览器会把Cookie保存起来.当浏览器再请求该网站时,浏览器把请求的网址连同该Cookie⼀Same as submitted to the server.服务器检查该Cookie,Identify this⽤户状态.服务器还可以根据需要修改Cookie 的内容.
At this time, the token information needs to be recorded on the server side,以及令牌对应的用户信息,这个就是Session mechanism to do the work.
2. 理解会话机制(Session)
The server may receive many requests at the same time,The server needs to distinguish who the user of each request is,It is necessary to record the token and user information of each user in the server.
The essence of all sessions is one“哈希表”,存储一些键值对结构,key 就是令牌的 ID(token/sessionId), value 就是 用户信息.
sessionId 和 token 就可以理解成是同一个东西的不同叫法(不同视角的叫法)

- 当用户登陆的时候, 服务器在 Session 中新增一个新记录, 并把 sessionId / token 返回给客户端. (例 如通过 HTTP 响应中的 Set-Cookie 字段返回).
- 客户端后续再给服务器发送请求的时候, 需要在请求中带上 sessionId/ token. (例如通过 HTTP 请求 中的 Cookie 字段带上).
- 服务器收到请求之后, 根据请求中的 sessionId / token 在 Session 信息中获取到对应的用户信息, 再进行后续操作.
注意:Servlet 的Session 是保存在内存中,重启服务器Session 数据就会消失,Equivalent to restarting a process.
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 No new cabinets will be added,ture Cabinets will be added
HttpSession session = req.getSession(true);
// 记录
session.setAttribute("Date",new Date());
resp.setCharacterEncoding("utf-8");
resp.setContentType("txt/plain");
resp.getWriter().print("办理会员成功!");
}
}b. Got it after the first visitCookie can be issued withCookie 的请求
@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 No new cabinets will be added,ture Cabinets will be added
HttpSession session = req.getSession(false);
if(session == null){
writer.println("no cabinets");
return;
}
Object o = session.getAttribute("Date");
if(o == null){
writer.println("There is a locker but the membership information is empty");
return;
}
Date date = (Date) o;
writer.println("有会员,Member information is:" + 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(); // Set the supported domain names,It is possible to support root domain names Domain name increases in scope
// cookie1.setPath(); // Set supported paths Path narrowed,一般默认为"/",in the root directoryCookie
// // 其它
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());
}
}
}本次分享就到这里,如果你喜欢这篇文章,请点赞加关注吧,或者如果你对文章有什么困惑,可以私信我.
边栏推荐
- C language inserted into the characters of simple exercises
- AntPathMatcher uses
- LeetCode刷题日记:74. 搜索二维矩阵
- libcurl访问url保存为文件的简单示例
- Data transfer at the data link layer
- 『网易实习』周记(二)
- Speed up your programs with bitwise operations
- FOFAHUB使用测试
- Outsourcing worked for three years, it was abolished...
- Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
猜你喜欢

The Paddle Open Source Community Quarterly Report is here, everything you want to know is here

Fly propeller power space future PIE - Engine Engine build earth science

Garbage Collector CMS and G1

Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation

LeetCode Brushing Diary: 74. Searching 2D Matrix

用位运算为你的程序加速

Scheduled tasks for distributed applications in Golang

AOF重写

Nanoprobes免疫测定丨FluoroNanogold试剂免疫染色方案

Use baidu EasyDL implement factory workers smoking behavior recognition
随机推荐
【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
哈希冲突和一致性哈希
AntPathMatcher uses
Yunhe Enmo: Let the value of the commercial database era continue to prosper in the openGauss ecosystem
PHP 使用 PHPRedis 与 Predis
Data transfer at the data link layer
NIO's Sword
LeetCode brushing diary: 53, the largest sub-array and
nacos startup error, the database has been configured, stand-alone startup
个人博客系统项目测试
力扣(LeetCode)213. 打家劫舍 II(2022.08.01)
软件测试 接口自动化测试 pytest框架封装 requests库 封装统一请求和多个基础路径处理 接口关联封装 测试用例写在yaml文件中 数据热加载(动态参数) 断言
The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!
Redis 订阅与 Redis Stream
C语言之插入字符简单练习
AWR分析报告问题求助:SQL如何可以从哪几个方面优化?
Can Youxuan database import wrongly be restored?
优炫数据库导库导错了能恢复吗?