1、Cookie 饼干
1.1 什么是 Cookie?
1、Cookie 翻译过来是饼干的意思。
2、Cookie 是服务器通知客户端保存键值对的一种技术。
3、客户端有了 Cookie 后,每次请求都发送给服务器。
4、每个 Cookie 的大小不能超过 4kb
1.2 如何创建 Cookie(定位,流程)
注意:
Cookie是在服务端中创建。
可以使用反射来达到通过请求参数名来执行目标的方法(超链接的地址定位到--->servlet,请求参数的value值定位到--->servlet里面的方法)
流程:
测试:创建动态web工程,并配置tomact实例名和浏览器路径。
web.xml:
注意:BaseServlet不需要配置web.xml,因为他不需要被访问。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<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>
</web-app>
Servlet 程序中的代码:BaseServlet
说明:为了代码的复用,里面的代码很常用所以放在公共类中,别的类想要直接继承即可。
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
public abstract class BaseServlet extends HttpServlet {
private static final long serialVersionUID = 2659767917553822186L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决post请求中文乱码问题
// 一定要在获取请求参数之前调用才有效
req.setCharacterEncoding("UTF-8");
// 解决响应中文乱码问题
resp.setContentType("text/html; charset=UTF-8");
//获取请求参数(action=createCookie)的值:createCookie
String action = req.getParameter("action");
try {
//获取本类对象的
//this.getClass():通过反射获取类对象
//this.getClass().getDeclaredMethods():通过反射获取类对象中所有的方法对象
//this.getClass().getDeclaredMethod(参数1,参数2):通过反射获取类对象中的指定方法对象
// 参数1:方法名 参数2:参数(反射对象类型的参数)
// 获取action业务鉴别字符串,获取相应的业务 方法反射对象
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// System.out.println(method);
// 执行目标类的方法(对象名,普通类型的参数)
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Servlet 程序中的代码:CookieServlet
注意:要解决响应中文乱问题
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
private static final long serialVersionUID = -2002732176578416250L;
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1 创建Cookie对象 value值不能是中文
Cookie cookie = new Cookie("key4", "value4");
//2 通知客户端保存Cookie 服务器发给客户端的都是响应来做
resp.addCookie(cookie);
//1 创建Cookie对象 cookie可以一次性创建多个
Cookie cookie1 = new Cookie("key5", "value5");
//2 通知客户端保存Cookie
resp.addCookie(cookie1);//不能省略
resp.getWriter().write("Cookie创建成功");
}
}
cookie.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie</title>
<base href="http://localhost:8080/cookie-session/">
<style type="text/css">
ul li {
list-style: none;
}
</style>
</head>
<body>
<iframe name="target" width="500" height="500" style="float: left;"></iframe>
<div style="float: left;">
<ul>
<!--写这样的路径格式是因为:
1.上面使用了base标签:可以按照指定路径返回跳转
2.可以通过请求参数(action=createCookie)名定位到servlet中的方法名"
原因是使用了反射,具体查看BaseServlet中的代码。-->
<li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li>
<li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>
<li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li>
<li>Cookie的存活周期</li>
<li>
<ul>
<li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)</a></li>
<li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li>
<li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li>
</ul>
</li>
<li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li>
<li><a href="" target="target">Cookie的用户免登录练习</a></li>
</ul>
</div>
</body>
</html>
1.3 服务器如何获取 Cookie
服务器获取客户端的 Cookie 只需要一行代码:Cookie[ ] req.getCookies();
说明:Cookie创建在服务端,之后发送给客户端保存,客户端每次发送请求都会携带Cookie数据到服务端。之后服务端可以通过Cookie[ ] req.getCookies()来获取保存到的Cookie信息。
web.xml,cookie.html,BaseServlet同上。
Cookie 的工具类:
package com.atguigu.util;
import javax.servlet.http.Cookie;
public class CookieUtils {
/**
* 查找指定名称的Cookie对象
* @param name
* @param cookies
* @return
*/
public static Cookie findCookie(String name , Cookie[] cookies){
// 是否为null可以预防空指针异常,是否为0可以预防数组下标越界异常。
if (name == null || cookies == null || cookies.length == 0) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;//找不到值返回空
}
}
Servlet 程序中的代码:
package com.atguigu.servlet;
import com.atguigu.util.CookieUtils;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
private static final long serialVersionUID = -2002732176578416250L;
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();//获取的是cookie数组
//情况1:获取cookie数组
/*for (Cookie cookie : cookies) {
// getName方法返回Cookie的key(名)
// getValue方法返回Cookie的value值
resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
}*/
//情况2.1---方式一:获取cookie数组中指定的cookie,没有直接提供的方法,只能通过遍历获取。
Cookie bbCookie = null;
/* for (Cookie cookie : cookies) {
if ("key4".equals(cookie.getName())) {
bbCookie = cookie;
System.out.println(bbCookie);
break;
}
}*/
//情况2.2---方式二:封装成工具Api
bbCookie = CookieUtils.findCookie("key4", cookies);
// 如果不等于null,说明赋过值,也就是找到了需要的Cookie
if (bbCookie != null) {
resp.getWriter().write("找到了需要的Cookie");
}
}
}
1.4 Cookie 值的修改(不能是中文)
方案一:直接覆盖
1、先创建一个要修改的同名(指的就是 key)的 Cookie 对象
2、在构造器,同时赋于新的 Cookie 值。
3、调用 response.addCookie( Cookie );
方案二:获取到具体的cookie进行修改
1、先查找到需要修改的 Cookie 对象
2、调用 setValue()方法赋于新的 Cookie 值。
3、调用 response.addCookie()通知客户端保存修改
注意:
- 这2种方案都不支持传入的数据是中文,空格等号,逗号等等,想要传中文需要进行BASE64编码(文件下载时讲的)。----->tomact8.0以及之前的版本
- tomact8.5开始的版本可以写中文了,但是仍有空格问题—》用URL编码解析
测试:
web.xml,cookie.html,BaseServlet同上。
Cookie 的工具类:
package com.atguigu.util;
import javax.servlet.http.Cookie;
public class CookieUtils {
/**
* 查找指定名称的Cookie对象
* @param name
* @param cookies
* @return
*/
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;//找不到值返回空
}
}
Servlet 程序中的代码:
package com.atguigu.servlet;
import com.atguigu.util.CookieUtils;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
private static final long serialVersionUID = -2002732176578416250L;
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 方案一:
// 1、先创建一个要修改的同名的Cookie对象 之前创建的是key4 key5
// 2、在构造器,同时赋于新的Cookie值。
// Cookie cookie = new Cookie("key4","newValue1");
// 3、调用response.addCookie( Cookie ); 通知 客户端 保存修改
// resp.addCookie(cookie);
// 方案二:
// 1、先查找到需要修改的Cookie对象 req.getCookies():获取的是cookie数组
Cookie cookie = CookieUtils.findCookie("key4", req.getCookies());
if (cookie != null) {
// 2、调用setValue()方法赋于新的Cookie值。value值不支持中文,空格等号,逗号等等,要是支持需要进行BASE64编码(文件下载时讲的)
cookie.setValue("newValue2");
// 3、调用response.addCookie()通知客户端保存修改
resp.addCookie(cookie);
}
resp.getWriter().write("key1的Cookie已经修改好");
}
}
1.5 浏览器查看 Cookie:
谷歌浏览器如何查看 Cookie:
火狐浏览器如何查看 Cookie:
1.6 Cookie 生命控制
Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁(删除)
setMaxAge()
- 正数,表示在指定的秒数后过期(
指定秒数内浏览器关闭也不会失效
) - 负数,表示浏览器一关,Cookie 就会被删除(默认值就是是-1)
- 零,表示马上删除 Cookie
测试:
web.xml,cookie.html,BaseServlet同上。
Cookie 的工具类:
package com.atguigu.util;
import javax.servlet.http.Cookie;
public class CookieUtils {
/**
* 查找指定名称的Cookie对象
* @param name
* @param cookies
* @return
*/
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;//找不到值返回空
}
}
Servlet 程序中的代码:
package com.atguigu.servlet;
import com.atguigu.util.CookieUtils;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
private static final long serialVersionUID = -2002732176578416250L;
/**
* 默认的会话级别的Cookie(创建一个cookie)
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("defalutLife","defaultLife");
cookie.setMaxAge(-1);//设置存活时间
resp.addCookie(cookie);
}
/**
* 马上删除一个Cookie(删除一个已经在浏览器中保存的cookie)
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
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个小时的Cooie
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
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");
}
}
1.7 Cookie 有效路径 Path 的设置(获取工程路径)
Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器
。哪些不发。
path 属性是通过请求的地址来进行有效的过滤。
流程:在服务端设置好可以发送cookie的格式,把这个格式返回给客户端,这样客户端在发送请求时满足这个格式才能发送。
举例:
遵循精确匹配原则:
path属性格式:
CookieA path=/工程路径
CookieB path=/工程路径/abc
请求地址1 如下:
http://ip:port/工程路径/a.html
CookieA 发送 满足CookieA的路径格式发送
CookieB 不发送 不满足CookieB的路径格式
请求地址2 如下:
http://ip:port/工程路径/abc/a.html
CookieA 发送 都满足
CookieB 发送
测试:
web.xml,cookie.html,BaseServlet同上。
Servlet 程序中的代码:
package com.atguigu.servlet;
import com.atguigu.util.CookieUtils;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
private static final long serialVersionUID = -2002732176578416250L;
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("path1", "path1");
// getContextPath() ===>>>> 得到工程路径
// ServletContext 对象也可以调用这个方法,现在用的是request方法???
cookie.setPath( req.getContextPath() + "/abc" ); // ===>>>> /工程路径/abc
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有Path路径的Cookie");
}
}
输入原来的地址,cookie发送不成功。
改为指定格式的path浏览器地址。
1.8 Cookie 练习—免输入用户名登录
流程:
第一次访问:首先在浏览器输入地址访问服务器的login.jsp页面,然后服务器返回对应的页面login.jsp,在页面中点击提交按钮发送请求参数到服务器,通过数据库存入的用户名和密码对用户名和密码进行判断,如果正确则存入cookie中并返回给客户端保存cookie,如果错误则提示报错。
第二次访问:在浏览器输入地址访问服务器的login.jsp页面,在访问的同时会把cookie信息也发生给服务器,在服务器端的login.jsp页面中动态的获取cookie中的值 把用户名显示到login.jsp页面上,之后把带有用户名的login.jsp页面返回给客户端,此时我们就可以看到页面上不用登录就会有用户名了。
总结:就是把服务端判断用户名是正确的信息保存到浏览器的cookie中,之后在次发送请求时,把cookie中的数据(用户名)动态提取到页面中,这样服务器返回给浏览器的jsp页面上就了携带了用户名。
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.atguigu.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
</web-app>
login.jsp 页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/2/10
Time: 11:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/cookie-session/loginServlet" method="get">
<%--cookie是个El的隐含对象对象,通过隐含对象获value取值
解释:cookie的信息存在Map<String字符串,Cookie对象>集合中(里面是一个个的键值对),
这个map集合的名字是cookie
通过 map的名字.k值 获取到v值,v值是个Cookie对象,
在对象.name(底层调用getName())获取这个对象的属性name,
getName()就是Cookie类提供的获取cookie的key值的方法。
getValue()就是Cookie类提供的获取cookie的value值的方法。
--%>
用户名:<input type="text" name="username" value="${cookie.username.value}"> <br>
密码:<input type="password" name="password"> <br>
<input type="submit" value="登录">
</form>
</body>
</html>
LoginServlet 程序:
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = -3112689056167440965L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
//写死了,这个地方没用使用数据库
if ("wzg168".equals(username) && "123456".equals(password)) {
//登录 成功
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60 * 60 * 24 * 7);//当前Cookie一周内有效
resp.addCookie(cookie);
System.out.println("登录 成功");
} else {
// 登录 失败
System.out.println("登录 失败");
}
}
}
启动tomact服务器,在浏览器输入访问login.jsp的路径,并在页面输入正确的用户名和密码进行测试。
关闭浏览器后再次打开,输入访问login.jsp页面的地址进行测试,可以看到页面上自动携带用户名。
2、Session 会话(也是域对象)
2.1 什么是 Session 会话?
1、Session 就一个接口(HttpSession)。
2、Session 就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个 Session 会话。
4、Session 会话中,我们经常用来保存用户登录之后的信息。
2.2 Session的创建/获取,是否为新,id 号
1,request.getSession():创建和获取 Session
注意:此方法由HttpServletRequest
类提供。
说明:创建和获取的 API 是一样的
。
解释:
之前:是jsp的四大作用域也是在9大内置对象中,写在jsp页面中可以直接使用。
现在:是在servlet后端代码中使用域对象,(request是每次发送请求都会自动创建一个req对象,session则是需要你调用方法来创建对象)
第一次调用是:创建 Session 会话
之后调用都是:获取前面创建好的 Session 会话对象。
2,isNew(); 判断到底是不是刚创建出来的(新的)
true 表示刚创建
false 表示获取之前创建
3,每个会话都有一个身份证号。也就是 ID 值。而且这个 ID 是唯一的。
getId() 得到 Session 的会话 id 值。
测试:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<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>
</web-app>
session.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Session</title>
<base href="http://localhost:8080/cookie-session/">
<style type="text/css">
ul li {
list-style: none;
}
</style>
</head>
<body>
<iframe name="target" width="500" height="500" style="float: left;"></iframe>
<div style="float: left;">
<ul>
<li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li>
<li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储</a></li>
<li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li>
<li>Session的存活</li>
<li>
<ul>
<li><a href="sessionServlet?action=defaultLife" target="target">Session的默认超时及配置</a></li>
<li><a href="sessionServlet?action=life3" target="target">Session3秒超时销毁</a></li>
<li><a href="sessionServlet?action=deleteNow" target="target">Session马上销毁</a></li>
</ul>
</li>
<li><a href="" target="target">浏览器和Session绑定的原理</a></li>
</ul>
</div>
</body>
</html>
BaseServlet:
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
public abstract class BaseServlet extends HttpServlet {
private static final long serialVersionUID = 2659767917553822186L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决post请求中文乱码问题
// 一定要在获取请求参数之前调用才有效
req.setCharacterEncoding("UTF-8");
// 解决响应中文乱码问题
resp.setContentType("text/html; charset=UTF-8");
String action = req.getParameter("action");
try {
// 获取action业务鉴别字符串,获取相应的业务 方法反射对象
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// System.out.println(method);
// 调用目标业务 方法
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
SessionServlet:
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet {
private static final long serialVersionUID = 5712618769106888131L;
protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建和获取Session会话对象(注意类型是:HttpServletRequest )
HttpSession session = req.getSession();
// 判断 当前Session会话,是否是新创建出来的
boolean isNew = session.isNew();
// 获取Session会话的唯一标识 id
String id = session.getId();
resp.getWriter().write("得到的Session,它的id是:" + id + " <br /> ");
resp.getWriter().write("这个Session是否是新创建的:" + isNew + " <br /> ");
}
}
启动tomact服务器,在浏览器输入地址访问session.html页面进行测试
2.3 Session 域数据的存取
web.xml,session.htnl,BaseServlet同上
SessionServlet:
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet {
private static final long serialVersionUID = 5712618769106888131L;
/**
* 往Session中保存数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key1", "value1");
resp.getWriter().write("已经往Session中保存了数据");
}
/**
* 获取Session域中的数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//存和取的key要相同
Object attribute = req.getSession().getAttribute("key1");
resp.getWriter().write("从Session中获取出key1的数据是:" + attribute);
}
}
2.4 Session 生命控制
2.4.1 修改Session的默认时长(范围:当前tomact)
范围:对当前 Tomcat 服务器下所有Session的默认超时时长有效。
说明:Session 默认的超时时间长为 30 分钟。是因为在Tomcat 服务器的配置文件web.xml 中默认有以下的配置,它就表示配置了当前 Tomcat 服务器下所有的Session
默认超时时长为:30 分钟。
注意:这个值可以修改,但是一般不推荐
修改这个tomact配置文件的默认超时时间。
<session-config>
<session-timeout>30</session-timeout>
</session-config>
查看这个配置文件的session默认超时时间步骤:
1.启动tomact服务器,这个地址就是idea整合tomact的配置文件的位置。
2.复制这个路径到磁盘中,点击回车。
3.进入conf目录下的web.xml文件
4.可以看到默认配置为30分钟
2.4.2 修改Session的默认时长(范围:当前工程)
范围:只对当前工程下所有session的默认超时时长有效。
说明:如果说,你希望你的当前web工程默认的 Session 的超时时长为其它时长,但又不推荐通过tomact的配置文件来修改。你可以在你自己的 web.xml 配置文件中做以上相同的配置。就可以修改你的 web 工程所有 Seession 的默认超时时长。
<!--表示当前web 工程。创建出来的所有Session 默认是20 分钟超时时长-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
2.4.3 修改单个Session的超时时长(超时理解)
设置 Session 的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。
值为正数:设定 Session 的超时时长。
值为负数:表示永不超时(极少使用)
public void setMaxInactiveInterval(int interval)
获取Session的超时时间,如果之前没有设置过,则用的是tomact中xml配置文件配置的默认超时时长(30分钟)。
public int getMaxInactiveInterval()
让当前 Session 会话马上超时无效。
public void invalidate()
Session 超时的概念介绍:假设设置超时时间为3秒,timeout会依次递减。如果在设置的时间内再次发送请求,相当于重置了超时时间 timeout=3,所以session不会超时。相反两次请求超过设置的超时时间3秒,则Session会超时。
测试:
session.htnl,BaseServlet同上
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<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>
<!--表示当前web工程。创建出来 的所有Session默认是20分钟 超时时长-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
SessionServlet:
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet {
private static final long serialVersionUID = 5712618769106888131L;
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取了Session的默认超时时长
int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
resp.getWriter().write("Session的默认超时时长为:" + maxInactiveInterval + " 秒 ");
}
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 先获取Session对象
HttpSession session = req.getSession();
// 设置当前Session3秒后超时
session.setMaxInactiveInterval(3);
resp.getWriter().write("当前Session已经设置为3秒后超时");
}
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超时时长还没有超时,但是浏览器一关Session就失效了???
答:
- 首先:
因为Session 技术,底层其实是基于 Cookie 技术来实现的
,服务器每次创建session会话的时候都会创建一个cookie对象,而这个cookie的超时时间是session级别(即:cookie默认的超时时间为-1,负数表示浏览器一关,Cookie 就会被删除)。 - 其次:Cookie被删除,浏览器发送请求给服务器找不到session的id值,只能重新创建一个新的session。新的session里面当然不会保存之前session中的数据。
注意:
- session 并不是随着浏览器的关闭而关闭的,只不过浏览器关闭会导致cookie删除,进而导致创建一个新的session,老的session就失效了(失效指的是操作不了老的session的数据,而老的session在生命周期范围内仍然存在)。
- session只会随着其生命周期结束或者强制销毁
执行流程:服务器创建session的同时会创建一个cookie并通知客户端保存,里面的k是固定的名字JSESSIONID,v是session的id值,之后每次发送请求都会携带cookie到服务器,根据session的id值获取对应的session。如果把Cookie删除了,也就是说没有这个id值了,那么再次发送请求找不到id值只能是重新创建一个新的sesssion,之后创建一个cookie保存id值到客户端,客户端发送请求每次携带cookie…。