Cookie 和 Session
1、Cookie 饼干
什么是 Cookie?
<--
1、Cookie 翻译过来是饼干的意思。
2、Cookie 是服务器通知客户端保存键值对的一种技术。
3、客户端有了 Cookie 后,每次请求都发送给服务器。
4、每个 Cookie 的大小不能超过 4kb
-->
如何创建 Cookie
<--
Cookie 的创建
客户端(浏览器) 服务器(Tomcat)
没有 Cookie ---------------> 1.创建 Cookie 对象
Cookie cookie = new Cookie("key1","value1");
收到响应后,发现有 2.通知客户端保存 Cookie
set-cookie响应头,就 response.addCookie( cookie )
去看一下,有没有这个 通过响应头 Set-Cookie 通知客户端保存 Cookie
Cookie。没有就创建, <---------------
有就修改。 Set-Cookie: key1=value1
-->
Servlet 程序中的代码:
package com.sq.servlet;
import com.sq.utils.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{
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key1","value1");
resp.addCookie(cookie);
Cookie cookie1 = new Cookie("key2","value2");
resp.addCookie(cookie1);
resp.getWriter().write("Cookie 创建成功");
}
}
服务器如何获取 Cookie
<%--
服务器获取客户端的 Cookie 只需要一行代码:req.getCookies():Cookie[]
--%>
<!--
客户端(浏览器) 服务器(Tomcat)
有了 Cookie,如下: ---------------------------------------- > 获取客户端发送过来的 Cookie 只需要一行代码。
key1 = value1; request.getCookies(): 返回 Cookie[] 数组
-->
Cookie 的工具类:
package com.sq.utils;
import javax.servlet.http.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;
}
}
Servlet 程序中的代码:
package com.sq.servlet;
import com.sq.utils.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{
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for ( Cookie cookie : cookies ){
resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1",cookies);
if (iWantCookie != null){
resp.getWriter().write("找到了需要的 Cookie");
}
}
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key1","value1");
resp.addCookie(cookie);
Cookie cookie1 = new Cookie("key2","value2");
resp.addCookie(cookie1);
resp.getWriter().write("Cookie 创建成功");
}
}
Cookie 值的修改
package com.sq.servlet;
import com.sq.utils.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{
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key2",req.getCookies());
if(cookie != null){
cookie.setValue("newValue2");
resp.addCookie(cookie);
}
resp.getWriter().write("key2 的 Cookie 已经修改好了");
}
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for ( Cookie cookie : cookies ){
resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1",cookies);
if (iWantCookie != null){
resp.getWriter().write("找到了需要的 Cookie");
}
}
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key1","value1");
resp.addCookie(cookie);
Cookie cookie1 = new Cookie("key2","value2");
resp.addCookie(cookie1);
resp.getWriter().write("Cookie 创建成功");
}
}
浏览器查看 Cookie:
<%--
谷歌浏览器如何查看 Cookie:
--%>
<--
Application -> Cookies -> http://localhost:8080(包含: 刷新、删除全部Cookie、删除指定的Cookie)
-->
<%--
火狐浏览器如何查看 Cookie:
--%>
<--
存储 -> Cookies -> http://localhost:8080
-->
Cookie 生命控制
<%--
Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁(删除)
setMaxAge()
正数,表示在指定的秒数后过期
负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
零,表示马上删除 Cookie
--%>
package com.sq.servlet;
import com.sq.utils.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{
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key2",req.getCookies());
if(cookie != null){
cookie.setValue("newValue2");
resp.addCookie(cookie);
}
resp.getWriter().write("key2 的 Cookie 已经修改好了");
}
protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("life3600","life3600");
cookie.setMaxAge(60 * 60);
resp.addCookie(cookie);
resp.getWriter().write("已经创建了一个存活一小时的 Cookie");
}
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key2", req.getCookies());
if(cookie != null){
cookie.setMaxAge(0);
resp.addCookie(cookie);
resp.getWriter().write("key2 的 Cookie 已经被删除");
}
}
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("defalutLife","defaultLife");
cookie.setMaxAge(-1);
resp.addCookie(cookie);
}
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for ( Cookie cookie : cookies ){
resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1",cookies);
if (iWantCookie != null){
resp.getWriter().write("找到了需要的 Cookie");
}
}
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key1","value1");
resp.addCookie(cookie);
Cookie cookie1 = new Cookie("key2","value2");
resp.addCookie(cookie1);
resp.getWriter().write("Cookie 创建成功");
}
}
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 发送
--%>
package com.sq.servlet;
import com.sq.utils.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{
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("path1","path1");
cookie.setPath( req.getContextPath() + "/abc");
resp.addCookie(cookie);
resp.getWriter().write("创建一个带有 Path 路径的 Cookie");
}
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key2",req.getCookies());
if(cookie != null){
cookie.setValue("newValue2");
resp.addCookie(cookie);
}
resp.getWriter().write("key2 的 Cookie 已经修改好了");
}
protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("life3600","life3600");
cookie.setMaxAge(60 * 60);
resp.addCookie(cookie);
resp.getWriter().write("已经创建了一个存活一小时的 Cookie");
}
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key2", req.getCookies());
if(cookie != null){
cookie.setMaxAge(0);
resp.addCookie(cookie);
resp.getWriter().write("key2 的 Cookie 已经被删除");
}
}
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("defalutLife","defaultLife");
cookie.setMaxAge(-1);
resp.addCookie(cookie);
}
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for ( Cookie cookie : cookies ){
resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1",cookies);
if (iWantCookie != null){
resp.getWriter().write("找到了需要的 Cookie");
}
}
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key1","value1");
resp.addCookie(cookie);
Cookie cookie1 = new Cookie("key2","value2");
resp.addCookie(cookie1);
resp.getWriter().write("Cookie 创建成功");
}
}
Cookie 练习—免输入用户名登录
login.jsp 页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>cookie_session_13-login.jsp</title>
</head>
<body>
<form action="http://localhost:8080/cookie_session_13/loginServlet" method="get">
用户名: <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.sq.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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if("sq168".equals(username) && "123456".equals(password)){
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(60 * 60 * 24 * 7);
resp.addCookie(cookie);
System.out.println("登录 成功");
} else {
System.out.println("登录 失败");
}
}
}
2、Session 会话
什么是 Session 会话?
<%--
1、Session 就一个接口(HttpSession)。
2、Session 就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个 Session 会话。
4、Session 会话中,我们经常用来保存用户登录之后的信息。
--%>
如何创建 Session 和获取(id 号,是否为新)
<%--
如何创建和获取 Session。它们的 API 是一样的。
request.getSession()
第一次调用是:创建 Session 会话
之后调用都是:获取前面创建好的 Session 会话对象。
isNew(); 判断到底是不是刚创建出来的(新的)
true 表示刚创建
false 表示获取之前创建
每个会话都有一个身份证号。也就是 ID 值。而且这个 ID 是唯一的。
getId() 得到 Session 的会话 id 值。
--%>
Session 域数据的存取
package com.sq.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 {
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);
}
}
Session 生命周期控制
<%--
public void setMaxInactiveInterval(int interval) 设置 Session 的超时时间(以秒为单位),超过指定的时长,Session就会被销毁。
值为正数的时候,设定 Session 的超时时长。
负数表示永不超时(极少使用)
public int getMaxInactiveInterval()获取 Session 的超时时间
public void invalidate() 让当前 Session 会话马上超时无效。
Session 默认的超时时长是多少!
Session 默认的超时时间长为 30 分钟。
因为在 Tomcat 服务器的配置文件 web.xml中默认有以下的配置,它就表示配置了当前 Tomcat 服务器下所有的 Session 超时配置默认时长为:30 分钟。
<session-config>
<session-timeout>30</session-timeout>
</session-config>
如果说。你希望你的 web 工程,默认的 Session 的超时时长为其他时长。你可以在你自己的 web.xml 配置文件中做以上相同的配置。就可以修改你的 web 工程所有 Seession 的默认超时时长。
--%>
<?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">
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
<%--
如果你想只修改个别 Session 的超时时长。就可以使用上面的 API。setMaxInactiveInterval(int interval)来进行单独的设置。
session.setMaxInactiveInterval(int interval)单独设置超时时长。
Session 超时的概念介绍:
--%>
示例代码:
package com.sq.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 {
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key1","value1");
resp.getWriter().write("已经往 Session 中保存了数据");
}
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
resp.getWriter().write("Session 的默认超时时长为: " + maxInactiveInterval + "秒");
}
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setMaxInactiveInterval(3);
resp.getWriter().write("当前的 Session 已经设置为 3 秒后超时");
}
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object attribute = req.getSession().getAttribute("key1");
resp.getWriter().write("从 Session 中获取出 key1 的数据是: " + attribute);
}
protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
boolean isNew = session.isNew();
String id = session.getId();
resp.getWriter().write("得到的 Session,它的 id 是:" + id + " <br /> ");
resp.getWriter().write("这个 Session 是否是新建的: " + isNew + " <br /> ");
}
}
Session 马上被超时示例:
package com.sq.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 {
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.invalidate();
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);
}
protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
boolean isNew = session.isNew();
String id = session.getId();
resp.getWriter().write("得到的 Session,它的 id 是:" + id + " <br /> ");
resp.getWriter().write("这个 Session 是否是新建的: " + isNew + " <br /> ");
}
}