1、Cookie 饼干(客户端保存)
1.1 Cookie简介
① Cookie 是服务器通知客户端保存键值对的一种技术。
② 客户端有了Cookie 后,每次请求都发送给服务器。
③ 每个Cookie 的大小不能超过4kb
1.2 如何创建cookie
客户端代码。
<head>
<base href="http://localhost:8080/13_cookie_session/cookie.html" />
</head>
<body>
<!--action=createCookie说明用cookieServlet类中的createCookie方法-->
<a herf="cookieServlet?action=createCookie" target="target">Cookie的创建</a>
<a herf="cookieServlet?action=getCookie" target="target">Cookie的获取</a>
<a herf="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a>
</body>
服务端web.xml配置
<servlet>
<servlet-name>CookieServlet</servlet-name>
<servlet-class>com.atguigu.servlet.CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieServlet</servlet-name>
<url-pattern>/cookieServlet</url-pattern>
</servlet-mapping>
服务端代码
public class CookieServlet extends BaseServlet{
protected void createCookie(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
//1、创建Cookie对象
Cookie cookie= new Cookie("key1","value1");
//2、通知客户端保存Cookie
resp.addCookie(cookie);
//给客户端反馈创建成功
resp.getWriter().write("Cookie创建成功");
}
protected void doPost() throws ServletException,IOException{
resp.setContentType("text/html;charset=UTF-8"); //可解决响应中文乱码问题
}
}
F12进浏览器调试页面,可以在Application里面看到cookie
1.3 服务端如何获取cookie
服务器获取客户端的Cookie 只需要一行代码:req.getCookies() 返回Cookie[ ]数组
服务端代码
//工具类,查找指定名称的cookie
public class CookieUtils{
public static Cookie findCookie(String name, Cookie[] cookies){
if(name==null||cookies==null||cookies.length==0){
return null
}
for(Cookie cookie:cookies){
if(name.equals(cookie.getName())){
return cookie;
}
}
return null;
}
}
public class CookieServlet extends BaseServlet{
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws
ServletException,IOException {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
// getName 方法返回Cookie 的key(名)
// getValue 方法返回Cookie 的value 值
resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "]<br/>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
// for (Cookie cookie : cookies) {
// if ("key2".equals(cookie.getName())) {
// iWantCookie = cookie;
// break;
// }
// }
// 如果不等于null,说明赋过值,也就是找到了需要的Cookie
if (iWantCookie != null) {
resp.getWriter().write("找到了需要的Cookie");
}
}
}
1.4 cookie值的修改
① 先创建一个要修改的同名(指的就是key同名)的Cookie 对象,同时在构造器的第二个形参里面,赋于新的Cookie 值。
② 调用response.addCookie( Cookie );
public class CookieServlet extends BaseServlet{
protected void updateCookie() throws ServletException,IOException{
//创建一个同修改名的cookie对象,同时在构造器里面赋新值
Cookie cookie = new Cookie("key1","newValue");
//调用reponse.addCookie(cookie),通知客户端保存修改
resp.addCookie(cookie);
resp.getWritter().write("key1中的Cookie已经修改好了");
}
}
1.5 cookie生命控制
Cookie 的生命控制指的是如何管理Cookie 什么时候被销毁(删除)
setMaxAge()
① 正数,表示在指定的秒数后过期
② 负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
③ 零,表示马上删除Cookie
<head>
<base href="http://localhost:8080/13_cookie_session/cookie.html" />
</head>
<body>
<!--action=createCookie说明用cookieServlet类中的defaultLife方法-->
<a herf="cookieServlet?action=defaultLife" target="target">Cookie默认存活时间</a>
<a herf="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a>
<a herf="cookieServlet?action=life3600" target="target">Cookie存活1分钟</a>
</body>
服务端代码
public class CookieServlet extends BaseServlet{
protected void updateCookie() throws ServletException,IOException{
//创建一个同修改名的cookie对象,同时在构造器里面赋新值
Cookie cookie = new Cookie("key1","newValue");
//调用reponse.addCookie(cookie),通知客户端保存修改
resp.addCookie(cookie);
resp.getWritter().write("key1中的Cookie已经修改好了");
}
protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
Cookie cookie = new Cookie("life3600", "life3600");
cookie.setMaxAge(60 * 60); // 设置Cookie 一小时之后被删除。无效
resp.addCookie(cookie);
resp.getWriter().write("已经创建了一个存活一小时的Cookie");
}
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 先找到你要删除的Cookie 对象
Cookie cookie = CookieUtils.findCookie("key4", req.getCookies());
if (cookie != null) {
// 调用setMaxAge(0);
cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭
// 调用response.addCookie(cookie);
resp.addCookie(cookie);
resp.getWriter().write("key4 的Cookie 已经被删除");
}
}
1.6 Cookie 有效路径Path 的设置
Cookie 的path 属性可以有效的过滤哪些Cookie 可以发送给服务器。哪些不发。
path 属性是通过请求的地址来进行有效的过滤。
说明:
CookieA path=/工程路径
CookieB path=/工程路径/abc
请求地址如下:
① http://ip:port/工程路径/a.html
CookieA 发送
CookieB 不发送
② http://ip:port/工程路径/abc/a.html
CookieA 发送
CookieB 发送
前端代码
<head>
<base href="http://localhost:8080/13_cookie_session/cookie.html" />
</head>
<body>
<!--action=createCookie说明用cookieServlet类中的testPath方法-->
<a herf="cookieServlet?action=testPath" target="target">Cookie的路径设置</a>
</body>
服务端代码
public class CookieServlet extends BaseServlet{
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
Cookie cookie = new Cookie("path1", "path1");
// getContextPath() ===>>>> 得到工程路径
cookie.setPath( req.getContextPath() + "/abc" ); // ===>>>> /工程路径/abc
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有Path 路径的Cookie");
}
}
2、Session 会话(四个域对象之一)
2.1 Session会话简介(服务端保存)
① Session 就一个接口(HttpSession)。
② Session 就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
③ 每个客户端都有自己的一个Session 会话。
④ Session 会话中,我们经常用来保存用户登录之后的信息。
2.2 创建和 获取Session(id号,是否为新)
(1)创建语法:request.getSession()
说明
第一次调用是:创建Session 会话
之后调用都是:获取前面创建好的Session 会话对象。
(2)isNew(); 判断到底是不是刚创建出来的(新的)
true 表示刚创建
false 表示获取之前创建
说明:
每个会话都有一个身份证号。也就是ID 值。而且这个ID 是唯一的。
getId() 得到Session 的会话id 值。
exp:
前端
<head>
<base href="http://localhost:8080/13_cookie_session" />
</head>
<body>
<!--action=createCookie说明用cookieServlet类中的testPath方法-->
<a herf="sessionServlet?action=createOrGetSession" target="target">Cookie的路径设置</a>
</body>
服务端
public class SessionServlet extends BaseServlet{
protected void createOrGetSession(HttpServletRequest req,HttpServletResponse resp){
//创建和获取Session会话对象
HttpSession session = req.getSession();
//判断当前session会话,是否是新创建出来的
boolean isNew = session.isNew();
//获取session会话的唯一标识id
String id = session.getId();
resp.getWriter().write("得到的Session,它的id是:" + id + "<br />");
}
}
web.xml配置
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>com.atguigu.servlet.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionServlet</servlet-name>
<url-pattern>/sessionServlet</url-pattern>
</servlet-mapping>
2.3 Session 域数据的存取
小复习:域对象就是像Map一样存取数据
前端
<head>
<base href="http://localhost:8080/13_cookie_session" />
</head>
<body>
<!--action=createCookie说明用cookieServlet类中的testPath方法-->
<a herf="sessionServlet?action=createOrGetSession" target="target">Cookie的路径设置</a>
<a herf="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a>
<a herf="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a>
</body>
服务端
public class SessionServlet extends BaseSevlet{
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException{
req.getSession().setAttribute("key1","value1");
resp.getWriter().write("已经往Session中保存了数据");
}
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object attribute = req.getSession().getAttribute("key1");
resp.getWriter().write("从Session中获取出key1的数据是" + attribute);
}
}
2.4 Session的生命周期
(1)生命周期的常用方法
① public void setMaxInactiveInterval(int interval) 设置Session 的超时时间(以秒为单位),超过指定的时长,Session就会被销毁。
值为正数的时候,设定Session 的超时时长。
负数表示永不超时(极少使用)
② public int getMaxInactiveInterval() 获取Session 的超时时间
Session 默认的超时时间长为30 分钟。
说明:
Tomcat 服务器的配置文件web.xml 中默认有以下的配置,它就表示配置了当前Tomcat 服务器下所有的Session超时配置默认时长为:30 分钟。
//Tomcat服务器中web.xml
<session-config>
<session-timeout>30</session-timeout>
</session-config>
如果说。你希望你的web 工程,默认的Session 的超时时长为其他时长。你可以在你自己的web.xml 配置文件中做以上相同的配置。就可以修改你的web 工程所有Seession 的默认超时时长。
//自己工程中的web.xml
<session-config>
<session-timeout>20</session-timeout>
</session-config>
此时已经将默认超时时间改成20分钟了
③ public void invalidate() 让当前Session 会话马上超时无效。
(2)Session超时的概念介绍
(3)代码演示
前端
<head>
<base href="http://localhost:8080/13_cookie_session" />
</head>
<body>
<!--action=createCookie说明用cookieServlet类中的testPath方法-->
<a herf="sessionServlet?action=createOrGetSession" target="target">Cookie的路径设置</a>
<a herf="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a>
<a herf="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a>
<a herf="sessionServlet?action=life3" target="target">Session3秒超时销毁</a>
<a herf="sessionServlet?action=deleteNow" target="target">Session马上销毁</a>
</body>
服务端
public class SessionServlet extends BaseSevlet{
//获取Session的默认超时时长
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException{
int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
resp.getWriter().write("Session的默认超时时长为"+ maxInactiveInterval+ "秒");
}
//设置3秒后超时
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
// 先获取Session 对象
HttpSession session = req.getSession();
// 设置当前Session3 秒后超时
session.setMaxInactiveInterval(3);
resp.getWriter().write("当前Session 已经设置为3 秒后超时");
}
//Session马上被超时
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
// 先获取Session 对象
HttpSession session = req.getSession();
// 让Session 会话马上超时
session.invalidate();
resp.getWriter().write("Session 已经设置为超时(无效)");
}
}
2.5 浏览器和Session之间的关联内幕
Session 技术,底层其实是基于Cookie 技术来实现的。