案例:
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;
import java.lang.reflect.Method;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决请求的中文乱码问题
// 一定要在获取请求参数之前调用才有效
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);
// 调用目标业务 方法
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("key1", "value1");
response.addCookie(cookie);
response.getWriter().write("Cookie创建成功");
}
}
cookie.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<base href="http://localhost:8080/WebStudy/">
head>
<body>
<a href="cookieServlet?action=createCookie" >Cookie的创建a>
body>
html>
web.xml:
<servlet>
<servlet-name>CookieServletservlet-name>
<servlet-class>com.fox.servlet.CookieServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>CookieServletservlet-name>
<url-pattern>/cookieServleturl-pattern>
servlet-mapping>
服务器获取客户端的 Cookie 只需要一行代码:request.getCookies()
:返回的是Cookie[]
数组
案例:
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;
import java.lang.reflect.Method;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决请求的中文乱码问题
// 一定要在获取请求参数之前调用才有效
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();
}
}
protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
// getName方法返回Cookie的key(名)
// getValue方法返回Cookie的value值
response.getWriter().write("Cookie["+cookie.getName()+"="+cookie.getValue()+"]
");
}
}
}
cookie.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<base href="http://localhost:8080/WebStudy/">
head>
<body>
<a href="cookieServlet?action=getCookie" >获取Cookiea>
body>
html>
F12查看:
假如我们不想获取所有的Cookie,只想获取指定key的Cookie怎么办?
这在开发中经常用到,因此我们可以写一个工具类:
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;
}else {
for (Cookie cookie : cookies) {
if(name.equals(cookie.getName())){
return cookie;
}
}
}
return null;
}
}
Servlet:
import com.fox.util.CookieUtils;
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;
import java.lang.reflect.Method;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决请求的中文乱码问题
// 一定要在获取请求参数之前调用才有效
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();
}
}
protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
Cookie cookieIWant = CookieUtils.findCookie("key1", cookies);
if(cookieIWant!=null){
response.getWriter().write("找到了你想要的Cookie["+cookieIWant.getName()+"="+cookieIWant.getValue()+"]");
}
}
}
方案一:
response.addCookie( cookie );
// 1、先创建一个要修改的同名的 Cookie 对象
// 2、在构造器,同时赋于新的 Cookie 值。
Cookie cookie = new Cookie("key1","newValue1");
// 3、调用 response.addCookie( Cookie ); 通知 客户端 保存修改
response.addCookie(cookie);
方案二:
response.addCookie(cookie)
通知客户端保存修改// 1、先查找到需要修改的 Cookie 对象
Cookie cookie = CookieUtils.findCookie("key2", req.getCookies());
if (cookie != null) {
// 2、调用 setValue()方法赋于新的 Cookie 值。
cookie.setValue("newValue2");
// 3、调用 response.addCookie()通知客户端保存修改
response.addCookie(cookie);
}
Cookie 的生命周期控制指的是如何管理 Cookie 什么时候被销毁(删除)
我们可以调用Cookie的方法设置生命周期:
void setMaxAge(int expiry)
案例:
Servlet:
import com.fox.util.CookieUtils;
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;
import java.lang.reflect.Method;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决请求的中文乱码问题
// 一定要在获取请求参数之前调用才有效
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();
}
}
protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key3", "key3");
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("key1", req.getCookies());
if (cookie != null) {
// 调用 setMaxAge(0);
cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭
// 调用 response.addCookie(cookie);
resp.addCookie(cookie);
resp.getWriter().write("key1 的 Cookie 已经被删除");
}
}
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key2","value2");
cookie.setMaxAge(-1);//设置存活时间为负数,浏览器一旦关闭,则此cookie销毁
resp.addCookie(cookie);
resp.getWriter().write("已创建 一关闭浏览器就会销毁的Cookie");
}
}
cookie.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<base href="http://localhost:8080/WebStudy/">
head>
<body>
<a href="cookieServlet?action=defaultLife" >创建一个关闭浏览器就会销毁的Cookiea><br>
<a href="cookieServlet?action=deleteNow" >让key1的cookie立刻销毁a><br>
<a href="cookieServlet?action=life3600" >创建一个存活一个小时的Cookiea><br>
body>
html>
Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器,哪些不发。
Cookie 的 path 属性是通过请求的地址来进行有效的过滤。
例如:
CookieA 设置path=/工程路径
CookieB 设置path=/工程路径/abc
案例:
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");
}
平时我们在一些网页上输入用户名和密码成功登录后,下次登录常常会帮我们输入好用户名,我们只需要填写密码即可。
login.jsp:
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 {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
//解决响应的乱码问题
response.setContentType("text/html; charset=UTF-8");
//简略模拟数据库判断用户名密码是否正确
if("mike".equals(username)&&"123456".equals(password)){
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60*60*24*7);//设置当前cookie一周内有效
response.addCookie(cookie);
response.getWriter().write("登录成功");
}else {
response.getWriter().write("登录失败");
}
}
}
只要登录成功一次以后,哪怕关掉浏览器,一周以内再次来到登录界面,用户名也会帮我们写好:
request.getSession()
session.isNew();
判断到底是不是刚创建出来的(新的)session.getId()
可以得到 Session 的会话 id 值。案例:
Servlet:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
public class SessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决请求的中文乱码问题
// 一定要在获取请求参数之前调用才有效
request.setCharacterEncoding("UTF-8");
// 解决响应的中文乱码问题
response.setContentType("text/html; charset=UTF-8");
String action = request.getParameter("action");
try {
// 获取action业务鉴别字符串,获取相应的业务 方法反射对象
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// 调用目标业务 方法
method.invoke(this, request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 创建和获取Session会话对象
HttpSession session = request.getSession();
// 判断 当前Session会话,是否是新创建出来的
boolean isNew = session.isNew();
// 获取Session会话的唯一标识 id
String id = session.getId();
response.getWriter().write("得到的Session,它的id是:" + id + "
");
response.getWriter().write("这个Session是否是新创建的:" + isNew + "
");
}
}
web.xml:
<servlet>
<servlet-name>SessionServletservlet-name>
<servlet-class>com.fox.servlet.SessionServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>SessionServletservlet-name>
<url-pattern>/sessionServleturl-pattern>
servlet-mapping>
session.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<base href="http://localhost:8080/WebStudy/">
head>
<body>
<a href="sessionServlet?action=createOrGetSession" >session的创建和获取a><br>
body>
html>
再点击一次,则是获取之前创建这个session,id还是一样的:
Session也是一种域对象,可以通过setAttribute(String key,Object value)
和getAttribute(String key)
方法存取客户状态信息。
案例:
SessionServlet:
//往Session中保存数据
protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("key1","value1");
response.getWriter().write("已经往session中保存了数据");
}
//获取Session域中的数据
protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object attribute = request.getSession().getAttribute("key1");
response.getWriter().write("从session中获取出key1的数据是:"+attribute);
}
session.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<base href="http://localhost:8080/WebStudy/">
head>
<body>
<a href="sessionServlet?action=setAttribute" >session域数据的存储a><br>
<a href="sessionServlet?action=getAttribute" >session域数据的获取a><br>
body>
html>
public void setMaxInactiveInterval(int interval)
设置 Session 的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。public int getMaxInactiveInterval()
获取 Session 的超时时间public void invalidate()
让当前 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秒后超时");
}
立刻销毁:
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 先获取Session对象
HttpSession session = req.getSession();
// 让Session会话马上超时
session.invalidate();
resp.getWriter().write("Session已经设置为超时(无效)");
}
Session 默认的超时时长是多少?
Session 默认的超时时间长为 30 分钟。
这是因为在 Tomcat 服务器的配置文件 web.xml中默认有以下的配置,它就表示配置了当前 Tomcat 服务器下所有的 Session 超时配置默认时长为:30 分钟。
<session-config>
<session-timeout>30session-timeout>
session-config>
setMaxInactiveInterval(int interval)
来进行单独的设置。Session 超时的概念介绍:
Session超时指的是,客户端两次请求的最大间隔时长
假如设置完session三秒超时以后,客户端在过了两秒又发了一个请求到服务器,那么这个超时时间又重新从三秒开始倒数,三秒内没有请求才真正超时。
为什么没超过session的超时时长,关闭浏览器后,request.getSession().getId()
和之前的session的id不一样了?
关闭浏览器后, session数据并没有丢失,只是关闭浏览器后,因为cookie保存sessionID,服务器会根据cookie中sessionID获取session;而默认的cookie生命周期为浏览器的缓存,即关掉浏览器之后cookie就失效了,此时sessionID也就没有了。再次访问后,服务器又生成一个新的sessionID,此时request.getSession()
通过sessionID获取到的session就不是之前的session了。