1. Cookie
1.1 什么是 Cookie
1、Cookie 翻译过来是饼⼲的意思。
2、Cookie 是服务器通知客户端保存键值对的⼀种技术。
3、客户端有了 Cookie 后,每次请求都发送给服务器。
4、每个 Cookie 的⼤⼩不能超过 4kb
1.2 如何创建 Cookie
创建 CookieServlet
package com.dd.cookie;
import com.dd.javabase.BaseServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieServlet extends BaseServlet {
//创建cookie
public void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//1.创建 Cookie 对象
Cookie cookie=new Cookie("key1","value1");
Cookie cookie1=new Cookie("key1","value1");
//2.通知浏览器保存 Cookie 对象
response.addCookie(cookie);
response.addCookie(cookie1);
//3.响应
response.getWriter().write("Cookie 被创建了");
}
}
配置 web.xm
<?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.dd.cookie.CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieServlet</servlet-name>
<url-pattern>/cookieServlet</url-pattern>
</servlet-mapping>
</web-app>
在⻚⾯上添加请求地址
<!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>
<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="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li>
<li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>
<li><a href="" target="target">Cookie值的修改</a></li>
<li>Cookie的存活周期</li>
<li>
<ul>
<li><a href="" target="target">Cookie的默认存活时间(会话)</a></li>
<li><a href="" target="target">Cookie立即删除</a></li>
<li><a href="" target="target">Cookie存活3600秒(1小时)</a></li>
</ul>
</li>
<li><a href="" target="target">Cookie的路径设置</a></li>
<li><a href="" target="target">Cookie的用户免登录练习</a></li>
</ul>
</div>
</body>
</html>
在 CookieServlet 的 createCookie 中添加如下代码,解决响应中⽂乱码问题.
response.setContentType("text/html; charset=utf-8");
1.3 服务器如何获取 Cookie
通过 request.getCookies() API可以获取到所有的 Cookie 数组
public void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {//获取cookie数组
response.getWriter().write("cookie:"+cookie.getName()+"value:"+cookie.getValue());
if (cookie.getName().equals("key1"))//指定cookie
response.getWriter().write("cookie:"+cookie.getName()+"value:"+cookie.getValue());
}
}
将获取指定Cookie的代码抽取到⼯具类中
package com.dd.javabase;
import javax.servlet.http.Cookie;
public class CookieUtils {
public static Cookie getCookie(String name, Cookie[] cookies){
if(name==null || cookies==null || cookies.length == 0){
return null;
}
for (Cookie cookie : cookies) {
if(cookie.getName().equals(name)){
return cookie;
}
}
return null;
}
}
1.4 Cookie 值的修改
⽅案⼀:
- 先创建⼀个要修改的同名(指的就是 key)的 Cookie 对象
- 在构造器,同时赋于新的 Cookie 值。
- 调⽤ response.addCookie( Cookie );
public void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决响应中⽂乱码问题
response.setContentType("text/html; charset=utf-8");
Cookie cookie = new Cookie("key2", "newValue2");
response.addCookie(cookie);
response.getWriter().write("key2 的值已经修改了");
}
⽅案⼆:
- 先查找到需要修改的 Cookie 对象
- 调⽤ setValue()⽅法赋于新的 Cookie 值。
- 调⽤ response.addCookie()通知客户端保存修改
public void updateCookie(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//解决响应中⽂乱码问题
response.setContentType("text/html; charset=utf-8");
Cookie key3 = CookieUtils.getCookie("key3", request.getCookies());
if (key3 != null) {
key3.setValue("newValue3");
response.addCookie(key3);
}
1.5 浏览器查看 Cookie
1.5.1 ⾕歌浏览器
1.5.2 ⽕狐浏览器
1.6 Cookie ⽣命控制
Cookie 的⽣命控制指的是如何管理 Cookie 什么时候被销毁(删除)
setMaxAge()
正数,表示在指定的秒数后过期
负数,表示浏览器⼀关,Cookie 就会被删除(默认值是-1)
零,表示⻢上删除 Cookie
Cookie cookie = new Cookie("3600","3600");
cookie.setMaxAge(60*60);
response.addCookie(cookie);
Cookie cookie = new Cookie("deleteNow","deleteNow");
cookie.setMaxAge(0);
response.addCookie(cookie);
Cookie cookie = new Cookie("defaultLife","defaultLife");
cookie.setMaxAge(-1);
response.addCookie(cookie);
1.7 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 发送
Cookie cookie = new Cookie("path","path");
cookie.setPath(request.getContextPath()+"/aaa");
response.addCookie(cookie);
1.8 Cookie 练习
login.jsp
<%--
Created by IntelliJ IDEA.
User: Love
Date: 2020/9/8
Time: 21:22
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/loginServlet"method="get">
账号:<input type="text" name="username"
value="${cookie.username.value}"><br>
密码:<input type="password" name="password" value=""><br>
<input type="submit" value="登陆">
</form>
</body>
</html>
LoginServlet.java
package com.dd.login;
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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if("admin".equals(username) && "123456".equals(password)){
System.out.println("登陆成功");
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);
}else {
System.out.println("登陆失败");
}
}
}
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.dd.cookie.CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieServlet</servlet-name>
<url-pattern>/cookieServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.dd.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
</web-app>
2. Session
1、Session 就⼀个接⼝(HttpSession)。
2、Session 就是会话。它是⽤来维护⼀个客户端和服务器之间关联的⼀种技术。
3、每个客户端都有⾃⼰的⼀个 Session 会话。
4、Session 会话中,我们经常⽤来保存⽤户登录之后的信息。
2.2 如何创建 Session 和获取(id 号,是否为新)
如何创建和获取 Session。它们的 API 是⼀样的。
request.getSession()
第⼀次调⽤是:创建 Session 会话
之后调⽤都是:获取前⾯创建好的 Session 会话对象。
isNew(); 判断到底是不是刚创建出来的(新的)
true 表示刚创建
false 表示获取之前创建
每个会话都有⼀个身份证号。也就是 ID 值。⽽且这个 ID 是唯⼀的。
getId() 得到 Session 的会话 id 值。
SessionServlet.java
resp.setContentType("text/html; charset=utf-8");
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/>");
2.3 Session 域数据的存取
public void getAttribute(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
String value = req.getSession().getAttribute("key1");
resp.getWriter().write("Session中key1的值为:" + value);
}
public void setAttribute(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
req.getSession().setAttribute("key1","vaule1");
resp.getWriter().write("已经在Session中保存数据");
}
2.4 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 的默认超时时⻓。
<!--表示当前 web ⼯程。创建出来 的所有 Session 默认是 20 分钟 超时时⻓-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
如果你想只修改个别 Session 的超时时⻓。就可以使⽤上⾯的 API。setMaxInactiveInterval(int
interval)来进⾏单独的设置。
session.setMaxInactiveInterval(int interval)单独设置超时时⻓。
req.getSession().setMaxInactiveInterval(3);
resp.getWriter().write("Session的超时时间已经设置为3秒");
Seession 的默认超时时⻓。
<!--表示当前 web ⼯程。创建出来 的所有 Session 默认是 20 分钟 超时时⻓-->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
如果你想只修改个别 Session 的超时时⻓。就可以使⽤上⾯的 API。setMaxInactiveInterval(int
interval)来进⾏单独的设置。
session.setMaxInactiveInterval(int interval)单独设置超时时⻓。
req.getSession().setMaxInactiveInterval(3);
resp.getWriter().write("Session的超时时间已经设置为3秒");