文章目录:
1.介绍
- 来自于Servlet规范中提供一个工具类。
- 如果两个Servlet为同一个用户/用一个浏览器提供服务,此时借助于用户的cookie实现数据共享。
- cookie在现实生活中相当于用户的会员卡。
2.生命周期
- 在正常情况下,cookie存放在浏览器内存中。在浏览器关闭时,cookie将被销毁。
- 在命令控制下,可以要求浏览器将接收cookie存放在客户端计算机的硬盘上并指定存活时间。在存活时间范围内,关闭浏览器,关闭服务器,关闭计算机都不会导致cookie销毁。
cookie对象.setMaxAge(60); 在硬盘上存活1分钟。
3.应用举例
两个Servlet之间通过 Cookie 类实现数据共享。(OneServlet、TwoServlet)
3.1 代码部分
package com.songzihao.controller; 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 OneServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.创建Cookie对象 Cookie cookie1=new Cookie("key1","hello"); Cookie cookie2=new Cookie("key2","java"); //2.调用响应对象将cookie写入到响应头 response.addCookie(cookie1); response.addCookie(cookie2); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
package com.songzihao.controller; 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 TwoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.调用请求对象,读取请求头中所有的cookie Cookie cookieArray[]=request.getCookies(); //2.遍历循环数组,读取OneServlet在cookie存入的数据 for (Cookie cookie : cookieArray) { String key=cookie.getName(); String value=cookie.getValue(); System.out.println("共享数据名===" + key + ",共享数据===" + value); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
<?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>OneServlet</servlet-name> <servlet-class>com.songzihao.controller.OneServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OneServlet</servlet-name> <url-pattern>/one</url-pattern> </servlet-mapping> <servlet> <servlet-name>TwoServlet</servlet-name> <servlet-class>com.songzihao.controller.TwoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TwoServlet</servlet-name> <url-pattern>/two</url-pattern> </servlet-mapping> </web-app>
3.2 运行结果部分
4.实现原理图