当前位置:网站首页>Cookie技术&Session技术&ServletContext对象
Cookie技术&Session技术&ServletContext对象
2022-07-06 07:03:00 【aigo-2021】
一、Cookie技术
Http协议有一个特点,就是无状态,每次请求响应的数据不进行持久化保存。但是在做某些Web需求时,是需要记录用户的状态的。
Cookie技术能将一些用户的信息记录在客户端。通过ServletAPI 中提供的Cookie类,可以将数据存储到客户端的 cookie文件中,当发送请求时,cookie文件中的内容包含在http请求中。
实现将数据通过Cookie存储在客户端,在服务器端创建Cookie类的对象,将数据封装到Cookie对象中,通过 response对象将Cookie对象响应回客户端,客户端自动将Cookie的数据存储到客户端指定文件夹的Cookie文件中。
例如:访问一个TestServlet1 将一个姓名存储到客户端:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/text1.do")
public class TestServlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//将tom名字 存储到访问这个Servlet的客户端上
Cookie cookie = new Cookie("name1","tom");
cookie.setMaxAge(60*60*24);
resp.addCookie(cookie);
Cookie cookie1 = new Cookie("name2","jack");
cookie1.setMaxAge(60*60*24);
resp.addCookie(cookie1);
Cookie cookie2 = new Cookie("password","123");
cookie2.setMaxAge(60*60*24);
resp.addCookie(cookie2);
}
}
在浏览器访问 http:localhost:8080/emp/text1.do 设置中查看存储的Cookie数据
可以通过访问某个站点,在请求中获得这个站点的Cookie数据(客户端的)
@WebServlet("/text2.do")
public class TestServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
//获得 客户端存储的Cookie
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
System.out.println(cookie.getName()+","+cookie.getValue());
}
}
}
二、Session技术
Session是会话的意思,代表客户端和服务器的一个会话对象,存储在服务器上的一个对象。
当客户端访问了服务器,就会在服务器上创建一个会话对象,当客户端再次访问了服务器,使用的还是这个会话对象,在会话对象的有效期内没有产生任何的请求响应,会话对象将被销毁,tomcat的session的有效期默认是20分钟
服务器上有一个存储会话对象的散列表(哈希表),当浏览器访问了服务器时,服务器读取浏览器中Cookie中存 储的会话id。
三 、Session对象的生命周期
由于Session的生命周期长,可以向Session中存储一些数据,那么这些数据的生命周期就等同于session的生命周 期,例如登录状态要保存多久?只要有请求响应的操作,就要保存登录状态。
如何向Session中存储数据:
HttpSession接口提供了setAttribute方法,可以向Session对象中存储数据。
存储数据
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/text1.do")
public class TestServlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
//向Session对象中存储 姓名tom
//首先要获得session对象
HttpSession session = request.getSession();
//session对象中封装了一个Map对象,将数据存储到了Map中,通常也说存储到了Session的属性中
session.setAttribute("name1","tom");//key,value的形式存储
}
}
获取数据
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/text2.do")
public class TestServlet2 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
//获取Session中的数据
HttpSession session = request.getSession();
System.out.println(session.getAttribute("name1"));
}
}
获得Session数据,先访问text1.do,再访问text2.do
四、设置Session有效期
在web.xml中,设置session有效期,单位是分钟
<session-config>
<session-timeout>1</session-timeout><!--设置为1分钟-->
</session-config>
有效期内有没有请求响应,Session被销毁
当然,也可以通过调用HttpSession的方法,让Session对象失效
//让session失效
session.invalidate();
session失效和销毁是不同,session失效后无法获得其属性值,也不能再次失效了,不能做这些操作了,但 session对象还存在;session对象的销毁是Session对象不存在了,清除了。
五、ServletContext对象
ServletContext是Servlet上下文对象,又叫应用程序的上下文对象。在Web服务器(tomcat)启动时 ServletContext对象被创建,Web服务器销毁时,ServletContext对象被销毁。
ServletContext对象的生命周期 长于 Session
可以向ServletContext对象中存储一些数据,数据的生命周期与ServletContext的生命周期相同。 也是通过setAttribute和getAttribute方法进行存储和获取的
思考:
什么样的数据存在Session中?什么样的数据存在ServletContext中?
每个页面共享的数据存储到Session中;所有用户共享的数据存储到ServletContext中
边栏推荐
- At the age of 26, I changed my career from finance to software testing. After four years of precipitation, I have been a 25K Test Development Engineer
- leetcode6109. 知道秘密的人数(中等,周赛)
- 微信脑力比拼答题小程序_支持流量主带最新题库文件
- Briefly describe the differences between indexes, primary keys, unique indexes, and joint indexes in mysql, and how they affect the performance of the database (in terms of reading and writing)
- leetcode35. 搜索插入位置(简单,找插入位置,不同写法)
- Proteus -- Serial Communication parity flag mode
- idea控制台彩色日志
- A method to measure the similarity of time series: from Euclidean distance to DTW and its variants
- 配置树莓派接入网络
- 巴比特 | 元宇宙每日必读:中国互联网企业涌入元宇宙的群像:“只有各种求生欲,没有前瞻创新的雄心”...
猜你喜欢
【软件测试进阶第1步】自动化测试基础知识
【刷题】怎么样才能正确的迎接面试?
Reflex WMS中阶系列3:显示已发货可换组
Interface automation test framework: pytest+allure+excel
leetcode59. 螺旋矩阵 II(中等)
L'Ia dans les nuages rend la recherche géoscientifique plus facile
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
指尖上的 NFT|在 G2 上评价 Ambire,有机会获得限量版收藏品
基于PyTorch和Fast RCNN快速实现目标识别
Huawei equipment configuration ospf-bgp linkage
随机推荐
Refer to how customer push e-commerce does content operation
【软件测试进阶第1步】自动化测试基础知识
kubernetes集群搭建Zabbix监控平台
Every API has its foundation when a building rises from the ground
19. Actual memory management of segment page combination
Database basics exercise part 2
AttributeError: Can‘t get attribute ‘SPPF‘ on <module ‘models.common‘ from ‘/home/yolov5/models/comm
Introduction to ros2 installation and basic knowledge
Arduino tutorial - Simon games
Simple use of MySQL database: add, delete, modify and query
从autojs到冰狐智能辅助的心里历程
雲上有AI,讓地球科學研究更省力
What is the biggest problem that fresh e-commerce is difficult to do now
[daily question] 729 My schedule I
漏了监控:Zabbix对Eureka instance状态监控
BUU的MISC(不定时更新)
PCL实现选框裁剪点云
Oracle数据库11gr2使用tde透明数据加密报错ora28353,如果运行关闭wallet会报错ora28365,运行打开wallet就报错ora28353无法打开wallet
Bitcoinwin (BCW): the lending platform Celsius conceals losses of 35000 eth or insolvency
作者已死?AI正用艺术征服人类