一、Cookie
1. Cookie 的概念
① Cookie 是服务器通知客户端保存键值对
的一种技术
② 客户端有了 Cookie 后,每次请求都发送
给服务器
③ 每个 Cookie 是存储在客户机的文本文件,
它们保存了大量轨迹信息,每个 Cookie
的大小不超过 4 kb
2. 创建 Cookie
Servlet 程序中的代码:
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
//1 创建 Cookie 对象
Cookie cookie = new Cookie("key4", "value4");
//2 通知客户端保存 Cookie
resp.addCookie(cookie);
//1 创建 Cookie 对象
Cookie cookie1 = new Cookie("key5", "value5");
//2 通知客户端保存 Cookie
resp.addCookie(cookie1);
resp.getWriter().write("Cookie 创建成功");
}
3. 服务器获取 Cookie
① Cookie 的工具类:
public class CookieUtils {
// 查找指定名称的 Cookie 对象
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 中的代码:
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");
}
}
4. Cookie 值的修改
方案一:
// 方案一:
// 1、先创建一个要修改的同名的 Cookie 对象
// 2、在构造器,同时赋于新的 Cookie 值。
Cookie cookie = new Cookie("key1","newValue1");
// 3、调用 response.addCookie( Cookie ); 通知 客户端 保存修改
resp.addCookie(cookie);
方案二:
// 1、先查找到需要修改的 Cookie 对象
Cookie cookie = CookieUtils.findCookie("key2", req.getCookies());
if (cookie != null) {
// 2、调用 setValue()方法赋于新的 Cookie 值。
cookie.setValue("newValue2");
// 3、调用 response.addCookie()通知客户端保存修改
resp.addCookie(cookie);
}
5. 浏览器查看 Cookie
① 谷歌查看
② 火狐查看
6. Cookie 生命控制
setMaxAge()正 数,表示在 指定的秒数后过期负 数,表示浏览器一关,Cookie 就会被删除(默认值是 -1)零 ,表示 马上删除 Cookie
//设置存活 1 个小时的 Cooie
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");
}
//马上删除一个 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 已经被删除");
}
}
//默认的会话级别的 Cookie
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws
ServletException,IOException {
Cookie cookie = new Cookie("defalutLife","defaultLife");
cookie.setMaxAge(-1);//设置存活时间
resp.addCookie(cookie);
}
7. Cookie 有效路径 Path 的设置
path 属性是通过请求的地址来进行有效的过滤CookieA path=/工程路径CookieB path=/工程路径/abc请求地址如下:http://ip:port/工程路径 /a.htmlCookieA 发送CookieB 不发送http://ip:port/工程路径 /abc/a.htmlCookieA 发送CookieB 发送
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");
}
8. 免输入用户名输入
① login.jsp
<form action="http://localhost:8080/13_cookie_session/loginServlet" method="get">
用户名:<input type="text" name="username" value="${cookie.username.value}"> <br>
密码:<input type="password" name="password"> <br>
<input type="submit" value="登录">
</form>
② Login.Servlet 程序
@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("登录 失败");
}
}
二、Session
1. Session 的概念
① Session 就一个接口 (HttpSession)
② Session 就是会话,他是用来维护一个客户
端和服务器之间关联的一种技术
③ 每个客户端都有自己的一个 Session 会话
④ Session 会话中,我们经常用来保存用户登
录之后的信息
2. 如何创建 Session 和获取
① 创建和获取 Sessionrequest.getSession()第一次 调用是: 创建 Session 会话后面调用都是: 获取 前面创建好的 Session 会话对象。② isNew();判断到底是不是刚创建出来的(新的)true 表示 刚创建false 表示 获取 之前创建③ 每个会话都有一个 ID 值 (唯一)getId() 得到 Session 的会话 id 值。
3. Session 域数据的存取
//保存数据
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);
}
4. Session 生命周期控制
① 设置超时时间
public void setMaxInactiveInterval(int interval)设置 Session 的 超时时间 (以 秒 为单位),超过指定的时长,Session 就会被 销毁值为 正数 的时候,设定 Session 的超时时长。负数 表示永不超时(极少使用)
public int getMaxInactiveInterval()获取 Session 的超时时间public void invalidate()让当前 Session 会话马上超时无效
Session 默认的超时时间长为 30 分钟因为在 Tomcat 服务器的配置文件 web.xml 中默认有以下的配置,它就表示配置了当前 Tomcat服务器下 所有 的 Session,可修改超时配置默认时长为:30 分钟<session-config><session-timeout>30</session-timeout></session-config>
④ 单独设置
session.setMaxInactiveInterval(int interval)单独 设置超时时长
⑤ Session 超时的概念
示例:
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 已经设置为超时(无效)");
}
5. 浏览器和 Session 的关联