当前位置:网站首页>Cookie和Session的相关概念
Cookie和Session的相关概念
2022-07-01 18:46:00 【Dragon_qing】
Cookie和Session的相关概念
Cookie、Session
1.会话
会话: 用户打开了一个浏览器,点击了很多超链接,访问多个web次元,关闭浏览器,这个过程可以称之为会话
有状态会话: 带有访问记录的会话
1.服务端会给客户端一个cookie,客户端下次访问时携带cookie访问就可以了 cookie
2.服务端登记客户端访问过,下次访问时匹配到客户端; session
2.保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务器技术,利用这个技术,可以保存用户的会话信息,可以把信息或者数据保存在Session中。
常见场景:网站登录之后,下次不用再登录了,第二次访问直接就上去了!
3.Cookie
1.从请求中拿到cookie信息
2.服务器响应给客户端cookie

cookie相关方法:
Cookie[] cookies = req.getCookies(); //获得cookie
cookie.getName() //获得cookie中的键
cookie.getValue() //获得cookie中的值
new Cookie("LastLoginTime",System.currentTimeMillis()+"") //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie有效期
resp.addCookie(cookie); //响应给客户端一个cookie
案例:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
//判断cookie是否存在
if(cookies == null){
out.println("第一次访问网站");
}else{
out.write("您上一次访问的时间是:");
for (Cookie cookie : cookies) {
if("LastLoginTime".equals(cookie.getName())){
//获取cookie中的值
long time = Long.parseLong(cookie.getValue());
Date date = new Date(time);
DateFormat dfd = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.CHINA);
DateFormat dft = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINA);
out.write(dfd.format(date)+dft.format(date));
}
}
}
Cookie cookie = new Cookie("LastLoginTime",System.currentTimeMillis()+"");
//设置cookie有效期为一天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
cookie:一般会保存在本地的用户目录下appdate;
一个网站cookie是否存在上限?
- 一个cookie只能保存一个信息;
- 一个web网站可以给浏览器发送多个cookie,最多存放20个cookie;
- cookie大小有限制4kb
- 300个cookie浏览器上限
删除cookie:
- 不设置有效期,关闭浏览器,自动失效;
- 设置有效期时间为0;
注意:在cookie的值为中文时最好使用URLEncoder.encode()来进行编码,防止中文乱码。取值时用URLDecoder.decode()来解码。
4.Session(重点)
什么事session:
- 服务器会给每一个用户创建一个session对象
- 一个session独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
- 用户登录之后,整个网站都可以访问 -->保存用户的信息;

Session常用的方法
Session和cookie的区别:
- Cookie是把用户的数据写到用户的浏览器,浏览器保存(可以保存多个)
- session把用户的数据写到用户独占的Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
- session对象由服务器创建;
使用场景:
- 保存一个登录用户的信息;
- 购物车信息;
- 在整个网站中经常会使用的数据,我们将它保存到Session中;
使用session:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
//得到Session
HttpSession session = req.getSession();
//给session中存东西
session.setAttribute("name",new Person("张三",18));
//获取session的id
String id = session.getId();
//判断session是不是新创建的
if(session.isNew()){
out.write("session创建成功,ID:"+id);
}else{
out.write("session已经存在,id:"+id);
}
//Session创建的时候做了什么事
// Cookie jsessionid = new Cookie("JSESSIONID", id);
// resp.addCookie(jsessionid);
}
//Person类
public class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
获取session中的信息
//得到Session
HttpSession session = req.getSession();
Person name = (Person) session.getAttribute("name");
System.out.println(name);
注销session
//得到Session
HttpSession session = req.getSession();
session.removeAttribute("name");
//注销session
session.invalidate();
会话自动过期:web.xml配置
<!-- 设置Session的默认失效时间-->
<session-config>
<!-- 15分钟后session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
边栏推荐
- AAAI2020: Real-time Scene Text Detection with Differentiable Binarization
- 类加载机制
- Dom4j parsing XML, XPath retrieving XML
- optaplanner学习笔记(一)案例Cloud balance
- Interview questions for audio and video positions in Dachang -- today's headline
- The key to the success of digital transformation enterprises is to create value with data
- 241. Different Ways to Add Parentheses
- Basic use of MySQL
- 【let var const】
- 测试自学人必看:软件测试如何找测试项目?
猜你喜欢

Why has instagram changed from a content sharing platform to a marketing tool? How do independent sellers use this tool?

Solidity - contract structure - error - ^0.8.4 NEW

科技T3国产平台!成功搭载“翼辉国产实时系统SylixOS”

Case sharing: basic networking configuration of QinQ

Instagram 为何从内容共享平台变成营销工具?独立站卖家如何利用该工具?

Basic use of MySQL
![[go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function](/img/1e/bed6a761f07c052e43b1e3b1701760.png)
[go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function

GB28181之SIP协议

Oracle物理体系结构

A brief understanding of white box encryption technology
随机推荐
H264 encoding profile & level control
OpenCV视频质量诊断----视频遮挡诊断
Dom4j parsing XML, XPath retrieving XML
Basic use of MySQL
Les canaux de culture intensive s'efforcent de développer Fu Xin et Wei Shi jiajie pour organiser une conférence de formation sur les nouveaux produits
Download (export) PDF template file (such as approval form), and report error: invalid nested tag * * * found, expected closing tag***
数字化转型企业成功的关键,用数据创造价值
torch. nn. functional. Interpolate function
Learning records of building thingsboard, an Internet of things platform
Crunch简介、安装,使用Crunch制作密码字典
AAAI2020: Real-time Scene Text Detection with Differentiable Binarization
118. Yanghui triangle
集合对象值改变NULL值对象
Mysql查询结果去除换行
科技T3国产平台!成功搭载“翼辉国产实时系统SylixOS”
面试题 16.16. 部分排序-双指针法
Collect Tiktok video
torch.nn.functional.interpolate函数
Instagram 为何从内容共享平台变成营销工具?独立站卖家如何利用该工具?
JVM内存模型