当前位置:网站首页>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>
边栏推荐
- Define dichotomy lookup
- DTD modeling
- Proxy in ES6
- XML syntax, constraints
- Use the uni app demo provided by Huanxin to quickly realize one-on-one chat
- 类加载机制
- Opencv video quality diagnosis - VIDEO occlusion diagnosis
- Actual combat of flutter - fast implementation of audio and video call application
- ffmpeg 错误码
- GB28181的NAT穿透
猜你喜欢

Uni app product classification

解决VSCode下载慢或下载失败的问题

GB28181之SIP协议

对象的创建

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

数字化转型企业成功的关键,用数据创造价值
![Extensive reading of the paper [film: visual reasoning with a general condition layer]](/img/69/f4ba37a7eae34a7e698127c31b0161.png)
Extensive reading of the paper [film: visual reasoning with a general condition layer]

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

Audio and video, encoding and decoding related e-books, gadgets, packaged for free!

Detailed explanation of JUnit unit test framework
随机推荐
音频编解码基础知识
P2433 【深基1-2】小学数学 N 合一
Detailed explanation of JUnit unit test framework
Summary of SQL query de duplication statistics methods
How to correctly use vertx to operate redis (3.9.4 with source code analysis)
Dom4j parsing XML, XPath retrieving XML
CMU AI PhD 第一年总结
Collect Tiktok video
Axure does not display catalogs
商业智能BI开发和报表开发有什么本质区别?
下载(导出)pdf模板文件(比如:审批单),报错:Invalid nested tag *** found, expected closing tag ***
OpenCV视频质量检测--清晰度检测
事务隔离级别 gap锁 死锁
sql查询去重统计的方法总结
axure不显示元件库
MySQl的基本使用
新增订单如何防止重复提交
安装sharp报错
【无标题】
How to configure webrtc video streaming format for easygbs, a new version of national standard gb28181 video platform?