当前位置:网站首页>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>
边栏推荐
- 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
- torch. nn. functional. Interpolate function
- 狼人杀攻略:你当我好骗吗,我们相信谁!
- Mysql查询结果去除换行
- 下载(导出)pdf模板文件(比如:审批单),报错:Invalid nested tag *** found, expected closing tag ***
- Nat penetration of gb28181
- Shell高级进阶
- Use the uni app demo provided by Huanxin to quickly realize one-on-one chat
- 一文读懂C语言中的结构体
- ffmpeg AVFrame 转 cv::Mat
猜你喜欢
产品模块化设计的前世今生
Instagram 为何从内容共享平台变成营销工具?独立站卖家如何利用该工具?
Solidity - truncated and checked modes of arithmetic operations - new features of 0.8.0
Parallelism, concurrency and life cycle of threads
Basic use of MySQL
Introduction to relevant processes and functions of wechat official account development
What is the essential difference between Bi development and report development?
任务:拒绝服务DoS
Reading the paper [learning to discretely compose reasoning module networks for video captioning]
P2433 【深基1-2】小学数学 N 合一
随机推荐
[Mori city] random talk on GIS data (I)
利用win7漏洞进行系统登录密码破解
mysql 報錯 Can‘t create table ‘demo01.tb_Student‘ (errno: 150)*
Learning notes [Gumbel softmax]
mysql 报错 Can‘t create table ‘demo01.tb_Student‘ (errno: 150)*
Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
sql查询去重统计的方法总结
[untitled]
Axure does not display catalogs
English grammar_ Adjective / adverb Level 3 - precautions
[go ~ 0 to 1] day 5 July 1 type alias, custom type, interface, package and initialization function
博途V16 获取系统时间转换成字符串
DDR4 test-2
ffmpeg AVFrame 转 cv::Mat
Why has instagram changed from a content sharing platform to a marketing tool? How do independent sellers use this tool?
Intensive cultivation of channels for joint development Fuxin and Weishi Jiajie held a new product training conference
118. Yanghui triangle
Basic knowledge of audio coding and decoding
P2433 【深基1-2】小学数学 N 合一
Regular expression =regex=regular expression