当前位置:网站首页>Cookie 和 Session
Cookie 和 Session
2022-06-12 16:17:00 【金字塔端的蜗牛】
Cookie 和Session
去医院的挂号处,会获得一个就诊卡,卡上包含了当前患者的关键信息(相当于cookie)。
在各个科室都能刷就诊卡,刷就诊卡的时候,就可以通过医院的服务器,来获取到当前患者的一系列信息。(不只是身份信息,还有以往病例等)
就诊卡相当于Cookie
医院的数据服务器上,就保存着用户的信息,也就是通过session的方式来保存的。
HttpServletRequest 类中的相关方法
getSession
HttpServletRequest 类中的相关方法。
在调用getSession的时候具体要做的事情
- 创建会话
首先先获取到请求中cookie里面的sessionId字段(相当于是会话的身份标识)
判断这个sessionId是否在当前服务器上存在
如果不存在,则进入创建会话逻辑。
创建会话:会创建一个HttpSession对象,并且生成一个sessionId,接下来就会把这个sessionId作为key,把这个HttpSession对象作为value,把这个键值对,给保存到服务器内存的一个“哈希表”这样的结构中。
在然后,服务器就会返回一个HTTP响应,把sessionId通过Set-Cookie字段返回给浏览器。
浏览器就可以保存这个sessionId到Cookie中了。
实际并不一定真是哈希表,但是一定是类似的能够存储键值对的结构,并且这个数据是在内存中的。
- 获取会话
先获取到请求中的cookie里面的sessionId字段(也是会话的身份标识)
判定这个sessionId是否在当前服务器上存在(也就是哈希表中是否有)
如果有,就直接查询出这个HttpSession对象,并且通过返回值返回回去。
HttpSession
这个对象也是一个“键值对”的结构。
HttpSession里面的每个键值对,称为“属性”(Attribute)。
HttpSession里面提供了两个方法
(1)getAttribute(取键值对)
(2)setAttribute(存键值对)
getCookies
Cookie[] getCookies():获取到请求中的Cookie数据。
返回值是Cookie类型的数组,每个元素是一个Cookie对象,每个Cookie对象又包含了两个属性,name和value(还是键值对)
HTTP请求中的cookie字段就是按照键值对的方式组织的,这里的键值对,大概的格式,使用 ;来分割多个键值对,使用 =来分割键和值,这些键值对都会在请求中通过cookie字段传给服务器。服务器收到请求后,就会进行解析,解析成Cookie[] 这样的形式。

Cookie这里可以保存任意自定制的键值对
如果是一般的键值对,直接使用getCookies来获取
如果是特殊的键值对(表示sessionId的键值对),不需要使用getCookies,直接使用getSession,就帮我们自动从Cookie中取sessionId了。
HttpServletResponse 类中的相关方法

响应中可以根据addCookie这个方法,来添加一个Cookie信息到响应报文中。
这里添加的键值对,就会作为HTTP响应中的set-Cookie字段来表示。
网页登录
点击登录按钮,就会给服务器发送登录请求。

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理用户请求
String username=req.getParameter("username");
String password=req.getParameter("password");
//判定用户名密码是否正确
//正常来说,这个判定操作要放到数据库中进行存取的
//此处为了简单,就直接在代码中写死了,假设用户名是"zhangsan",密码是"123"
if("zhangsan".equals(username) && "123".equals(password)) {
//登录成功
resp.sendRedirect("index");
}else {
//登录失败
resp.getWriter().write("login failed");
}
}
}
在后续跳转到index的时候,服务器要能够获取到当前用户的身份信息,因此需要创建一个session供后面来使用。并且在session中填写上一些必要的身份信息,以供后面来使用。
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理用户请求
String username=req.getParameter("username");
String password=req.getParameter("password");
//判定用户名密码是否正确
//正常来说,这个判定操作要放到数据库中进行存取的
//此处为了简单,就直接在代码中写死了,假设用户名是"zhangsan",密码是"123"
if("zhangsan".equals(username) && "123".equals(password)) {
//登录成功
//创建会话,保存必要的身份信息
HttpSession httpSession= req.getSession(true);
//往会话中存储键值对,必要的身份信息
httpSession.setAttribute("username",username);
resp.sendRedirect("index");
}else {
//登录失败
resp.getWriter().write("login failed");
}
}
}
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//返回一个主页(主页就是一个简单的html片段)
//需要得到用户名是啥,从httpsession中就能拿到
//此处getSession的参数必须是false,前面在登录的过程中,已经创建过会话了,此处是要直接获取到之前的会话
HttpSession session=req.getSession(false);
String username=(String)session.getAttribute("username");
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("<h3>欢迎你"+username+"</h3>");
}
}
<body>
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="登录">
</form>
</body>
会话里,是可以保存任意指定的用户信息的
在此处,就可以实现一个功能,记录当前用户访问主页的次数。
当登录之后,首次访问主页,主页上就显示,当前访问了1次,当刷新页面,次数就会累加。
上传文件
也是开发中一个典型的需求
上传文件的时候,在前端需要用到form表单
form表单中,需要使用一个特殊的类型 form-data
此时提交文件的时候,浏览器就会把文件内容以form-data的格式构造到HTTP请求中。服务器就可以通过getPart来获取了。
一个HTTP请求,可以一次性提交多个文件
每个文件都称为一个part,每个part都有一个name(身份标识),服务器代码中就可以根据name找到对应的part。
基于这个part就可以进一步获取到文件信息,并进行下一阶段操作
Part 类方法如下:

@MultipartConfig
@WebServlet("/upload")
public class UpLoadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Part part= req.getPart("MyImage");
System.out.println(part.getSubmittedFileName());
System.out.println(part.getContentType());
System.out.println(part.getSize());
part.write("e:/画图板/aaa.jpg");
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write("上传成功");
}
}
<body>
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="MyImage">
<input type="submit" value="提交">
</form>
</body>
边栏推荐
- Global and Chinese market of vascular prostheses 2022-2028: Research Report on technology, participants, trends, market size and share
- 借助SpotBugs将程序错误扼杀在摇篮中
- 【周赛复盘】LeetCode第80场双周赛
- acwing 790. 数的三次方根(浮点数二分)
- Interview: difference between '= =' and equals()
- < 山东大学软件学院项目实训 > 渲染引擎系统——基础渲染器(三)
- Global and Chinese markets of three-phase induction motors 2022-2028: Research Report on technology, participants, trends, market size and share
- < 山东大学软件学院项目实训 > 渲染引擎系统——基础渲染器(四)
- acwing 797 差分
- 深入理解 Go Modules 的 go.mod 与 go.sum
猜你喜欢

Review of the development of China's medical beauty (medical beauty) industry in 2021: the supervision is becoming stricter, the market scale is expanding steadily, and the development prospect is bro

统计机器学习代码合集

批量--03---CmdUtil

acwing 801. 二进制中1的个数(位运算)

acwing 798二维差分(差分矩阵)

Batch --04--- moving components

大规模实时分位数计算——Quantile Sketches 简史

Step by step steps to create an ABAP program with a custom screen

When programming is included in the college entrance examination...

The small flying page is upgraded to be intelligent and the bug repair is faster
随机推荐
Development practice of ag1280q48 in domestic CPLD
你的下一台电脑何必是电脑,探索不一样的远程操作
Global and Chinese markets of automatic glue applicators 2022-2028: Research Report on technology, participants, trends, market size and share
Batch --03---cmdutil
<山东大学项目实训>渲染引擎系统(二)
[tool recommendation] personal local markdown knowledge map software
The common hand, the original hand and the excellent hand from the sum of Fibonacci sequence
generate pivot data 2
The C Programming Language(第 2 版) 笔记 / 8 UNIX 系统接口 / 8.6 实例(目录列表)
acwing 790. The cubic root of a number (floating-point number in half)
Read MHD and raw images, slice, normalize and save them
<山东大学项目实训>渲染引擎系统(六)
Office VR porn, coquettish operation! The father of Microsoft hololens resigns!
< 山东大学软件学院项目实训 > 渲染引擎系统——辐射预计算(九)
Global and Chinese market of vascular prostheses 2022-2028: Research Report on technology, participants, trends, market size and share
acwing 802. 区间和 (离散化)
Step by step steps to create an ABAP program with a custom screen
< 山东大学软件学院项目实训 > 渲染引擎系统——基础渲染器(六)
Example of bit operation (to be continued)
联通网管协议框图
