cookie 生命周期和cookie有效路径超级详细讲解

文章目录

  • cookie 生命周期和cookie有效路径超级详细讲解
    • cookie 生命周期
      • 介绍
      • 代码示例
      • 完成测试 , 注意抓包看数据
    • cookie 有效路径
      • 有效路径规则
      • 规则如下:
        • 代码示例
        • 完成测试 , 注意抓包看创建 Cookie 时,返回的数据
        • 完成测试 , 注意抓包看读取 Cookie 时,返回的数据
      • 代码示例
        • html页面
        • 创建LoginServlet
    • Cookie 注意事项和细节
      • 代码解决
        • 设置
        • 解码

cookie 生命周期和cookie有效路径超级详细讲解

cookie 生命周期

介绍

  1. Cookie 的生命周期指的是如何管理 Cookie 什么时候被销毁(删除)

  2. setMaxAge()

​ ● 正数,表示在指定的秒数后过期

​ ● 负数,表示浏览器关闭,Cookie 就会被删除(默认值是-1)

​ ● 0,表示马上删除 Cookie

代码示例

public class CookieLive extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("CookieLive 被调用...");

        //演示创建一个cookie , 生命周期为 60s
        Cookie cookie = new Cookie("job", "java");
        //解读:
        // 1. 从创建该cookie开始计时, 60秒后无效
        // 2. 浏览器来根据创建的时间,计时到60s秒,就认为该cookie无效
        // 3. 如果该cookie无效,那么浏览器在发出http请求时,就不在携带该cookie
        cookie.setMaxAge(60);
        //将cookie保存到浏览器
        response.addCookie(cookie);


        //演示如何删除一个cookie, 比如删除username
        //1 先得到username cookie
        Cookie[] cookies = request.getCookies();
        Cookie usernameCookie =
                CookieUtils.readCookieByName("username", cookies);
        if(usernameCookie != null) {
            //2. 将其生命周期设置为0
            usernameCookie.setMaxAge(0);
            //3. 重新保存该cookie, 因为你将其生命周期设置0, 就等价于让浏览器删除该cookie
            //4. 说明:该cookie会被浏览器直接删除
            //   返回一个Set-Cookie: xxxxx => 一会抓包.
            //   Set-Cookie: username=tom; Expires=Thu, 01-Jan-1970 00:00:10 GMT
            response.addCookie(usernameCookie);//返回一个Set-Cookie: xxxxx => 一会抓包.
        }else{
            System.out.println("没有找到该cookie, 无法删除...");
        }

        /***********************
         * 默认的会话级别的 Cookie [即浏览器关闭就销毁了]
         * 前面我们讲课时,都是默认会话级别的生命周期
         ***********************/
        Cookie cookie3 = new Cookie("dkey", "dkey_value");
        /**
         * 解读 setMaxAge源码
         * public void setMaxAge(int expiry) {
         *         this.maxAge = expiry;
         * }
         * private int maxAge = -1; 默认就是-1
         */
        //cookie.setMaxAge(-1);//设置存活时间
        response.addCookie(cookie3);


        // 给浏览器返回信息
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>设置cookie生命周期</h1>");
        writer.flush();
        writer.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

完成测试 , 注意抓包看数据

在这里插入图片描述

cookie 有效路径

有效路径规则

  1. Cookie 有效路径 Path 的设置

  2. Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器。哪些不发。path属性是通过请求的地址来进行有效的过滤

规则如下:

cookie1.setPath = /工程路径

cookie2.setPath = /工程路径/aaa

请求地址: http://ip:端口/工程路径/资源

cookie1 会发给服务器

cookie2 不会发给服务器

请求地址: http://ip:端口/工程路径/aaa/资源

cookie1 会发给服务器

cookie2 会发给服务器

代码示例

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 CookiePathServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Cookie cookie = new Cookie("keyPath1", "keyPath1Value");
        // request.getContextPath() + "/aaa" 得到 /工程路径/aaa
        cookie.setPath(request.getContextPath() + "/aaa");
        Cookie cookie2 = new Cookie("keyPath2", "keyPath2Value");
        cookie2.setPath(request.getContextPath());
        response.addCookie(cookie);
        response.addCookie(cookie2);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("<h1>创建 Cookie keyPath1 路径 /工程路径/aaa </h1>");
        response.getWriter().write("<h1>创建 Cookie keyPath2 路径 /工程路径 </h1>");
    }
}

完成测试 , 注意抓包看创建 Cookie 时,返回的数据

在这里插入图片描述

完成测试 , 注意抓包看读取 Cookie 时,返回的数据

在这里插入图片描述

代码示例

需求: 完成自动填写登录账户应用案例 , 如果用户登录成功,则下次登录自动填写登录 账户

html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<h1>用户登录界面</h1>
<form action="#" method="post">
    u:<input type="text" name="username"><br/>
    p:<input type="password" name="pwd"><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

创建LoginServlet

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("LoginServlet 被调用...~~~");

        //1. 接收表单提交用户名和密码
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //2. 判断是否合法
        if ("xxxx".equals(username) && "123456".equals(pwd)) {
            //将登录成功的用户名,以cookie的形式,保存到浏览器
            Cookie loginuserCookie = new Cookie("loginuser", username);
            //设置该cookie生命周期
            loginuserCookie.setMaxAge(3600 * 24 * 3);
            response.addCookie(loginuserCookie);
            //合法
            writer.println("<h1>登录OK</h1>");

        } else {
            //不合法
            writer.println("<h1>登录失败</h1>");
        }

        writer.flush();
        writer.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

Cookie 注意事项和细节

  1. 一个 Cookie 只能标识一种信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。

  2. 一个 WEB 站点可以给一个浏览器发送多个 Cookie,一个浏览器也可以存储多个 WEB 站点提供的 Cookie。

  3. cookie 的总数量没有限制,但是每个域名的 COOKIE 数量和每个 COOKIE 的大小是有限制的 (不同的浏览器限制不同, 知道即可) , Cookie 不适合存放数据量大的信息。

  4. 注意,删除 cookie 时,path 必须一致,否则不会删除

  5. Java servlet 中 cookie 中文乱码

说明 如果存放中文的 cookie, 默认报错, 可以通过 URL 编码和解码来解决, 不建议存 放中文的 cookie 信息

代码解决

设置

public class EncoderCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("EncoderCookie 被调用");
        //1. 创建cookie, 有中文

        //1) 如果直接存放中文的cookie, 报错 Control character in cookie value or attribute.
        //2) 解决方法,就是将中文 编程成 URL编码  英文: Encode=编码
        //3) 编码后,再保存即可
        String company = URLEncoder.encode("大家好", "utf-8");

        Cookie cookie = new Cookie("company", company);
        //2. 保存到浏览器
        response.addCookie(cookie);

        //3. 给浏览器返回信息
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>设置中文cookie成功</h1>");
        writer.flush();
        writer.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

解码

public class ReadCookie2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("ReadCookie2 被调用..");
        //读取到中文cookie
        Cookie[] cookies = request.getCookies();
        Cookie companyCookie = CookieUtils.readCookieByName("company",cookies);
        String companyVal = companyCookie.getValue();
        System.out.println("companyVal= " + companyVal);//URL

        //解码
        companyVal = URLDecoder.decode(companyVal, "utf-8");
        System.out.println("解码后 companyVal= " + companyVal);//中文

        //3. 给浏览器返回信息
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>读取中文cookie解码成功~</h1>");
        writer.flush();
        writer.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/38332.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

bug:file name too long文件名超出系统最大限制

各操作系统支持最长的文件和目录名称长度&#xff08;Linux、Win、Mac&#xff09; 今天开发需求的时候发现无法新建文件&#xff0c;提示file name too lang&#xff0c;于是翻阅和查询了一些资料&#xff0c;发现不同操作系统下文件名和目录名最长的长度不同。 操作系统文件名…

elementUI 非表单格式的校验

在普通表单中对输入框、选择框都有校验案例。 但是在自定义非空中如何进行校验官网并没有说明 关键代码 clearValidate 方法清除校验 this.$refs.formValue.clearValidate(signinimg) 使用案例 <template><div class"stylebg"><Tabs icons"el-…

.net6中WPF的串口通信和USB通信

之前写过串口通信&#xff0c;不过是winform的。 c#使用串口进行通信_c# 串口通信_故里2130的博客-CSDN博客 今天说一下&#xff0c;.net6中wpf的串口通信和USB通信&#xff0c;在工控行业中&#xff0c;这2种的方式非常多&#xff0c;还有网口通信&#xff0c;它们都是用来和…

利用ChatGPT场景化学习英语听说读写

大家好&#xff0c;我是可夫小子&#xff0c;关注AIGC、读书和自媒体。解锁更多ChatGPT、AI绘画玩法。加我&#xff0c;备注&#xff1a;chatgpt&#xff0c;拉你进群。 我们从初中就开始学习英语&#xff0c;到大学也有小十年&#xff0c;在这个过程中&#xff0c;我们投入了很…

提高驾驶安全性 | 基于ACM32 MCU的胎压监测仪方案

概述 作为车辆的基础部件&#xff0c;轮胎是影响行车安全不可忽视的因素之一。据统计&#xff0c;中国每年由胎压问题引起轮胎爆炸的交通事故约占 30%&#xff0c;其中 50%的高速交通事故是由车辆胎压异常引起。因此&#xff0c;准确实时地监测车辆在行驶过程中的轮胎压监测系…

Java List中通过对象属性排序,可实现多条件排序

直接上代码&#xff1a; import com.google.common.collect.Lists; import lombok.AllArgsConstructor; import lombok.Data;import java.util.Comparator; import java.util.List; import java.util.stream.Collectors;/*** List 对象属性排序*/Data AllArgsConstructor clas…

【Linux】进程概念

【Linux】进程概念 文章目录 【Linux】进程概念1、冯诺依曼体系结构2、操作系统2.1 概念2.2 设计OS的目的2.3 定位2.4 管理2.5 系统调用和库函数概念 3、进程3.1 基本概念3.2 描述进程—PCB3.3 组织进程3.4 查看进程3.5 获取进程标示符3.6 创建进程-fork初识3.7 进程状态3.7.1 …

Vue2 ➔ Vue3 都做了哪些改变?

不是吧&#xff0c;兄弟&#xff0c;Vue3 都出来多久了&#xff0c;你还对这个感兴趣&#xff0c;说&#xff01;是不是没好好卷&#xff1f;&#x1f60f; 俺也一样 &#x1f602;&#xff0c;Vue3 出来之后只是简单了解了一下&#xff0c;然后还是转头一直在写 Vue2。当然&a…

IIC的再认识

IIC介绍 关于IIC的基本概念&#xff0c;其实在学习89C52的时候已经大致了解过了&#xff0c;且由于STM32支持了IIC协议&#xff0c;所以在STM32中使用IIC可以直接调用HAL库的库函数&#xff1a; HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c,uint16_t DevAdd…

IP基础知识总结

IP他负责的是把IP数据包在不同网络间传送&#xff0c;这是网络设计相关的&#xff0c;与操作系统没有关系。所以这部分知识&#xff0c;不是网络的重点。IP和路由交换技术联系紧密。但是要作为基本知识点记住。 一、基本概念 网络层作用&#xff1a;实现主机与主机之间通信。 …

瀚高企业版数据库V6单机安装指导手册(Linux)

目录 瀚高企业版数据库V6单机安装指导手册&#xff08;Linux&#xff09; 1. 环境准备 1.1 防火墙设置 1.1.1 开放数据库使用端口 1.1.2 关闭防火墙 1.2 检查时区和时间 1.3 创建highgo用户 1.4 检验安装包 2. 软件安装 2.1 图形化安装 3. 设置highgo用户环境变量 4.…

mysql 1 -- 数据库介绍、mysql 安装及设置

Linux 安装 mysql 1、数据库&#xff08;mysql&#xff09; 数据文件 - 数据库过了系统 2、c/s mysql 服务器 mysql 客户端 ip port : 3306 3、关系型 于 非关系型数据库&#xff08;nosql&#xff09; nosql可以解决一些关系型数据库所无法实现的场景引用。 一、数据库介绍 …

计算机网络——三次握⼿、四次挥手

TCP 三次握手 1、第⼀个SYN报⽂&#xff1a; 客户端随机初始化序列号client_isn&#xff0c;放进TCP⾸部序列号段&#xff0c; 然后把SYN置1。把SYN报⽂发送给服务端&#xff0c;表⽰发起连接&#xff0c; 之后客户端处于SYN-SENT状态。 2、第⼆个报⽂SYNACK报⽂&#xff1a; …

郑州网站域名升级https通配符证书

新创建的网站如果没有安装SSL证书&#xff0c;在客户端与服务器传输信息时会使用明文传输&#xff0c;明文传输的数据容易被其他人截获或者插入违法信息&#xff0c;会对网站所有者和访问网站的客户带来危害。而部署了SSL证书将网站域名由http升级为https&#xff0c;会在客户端…

卷积神经网络(CNN)原理详解

近些年人工智能发展迅速&#xff0c;在图像识别、语音识别、物体识别等各种场景上深度学习取得了巨大的成功&#xff0c;例如AlphaGo击败世界围棋冠军&#xff0c;iPhone X内置了人脸识别解锁功能等等&#xff0c;很多AI产品在世界上引起了很大的轰动。 而其中 卷积神经网络&am…

G1垃圾收集器-JVM(十三)

上篇文章说了CMS垃圾收集器使用以及三色标记如何解决cms的一些问题。分别有初始标记&#xff0c;并发标记&#xff0c;重新标记&#xff0c;并发清理&#xff0c;并发重置。 CMS垃圾收集器&三色标记-JVM&#xff08;十二&#xff09; G1收集器&#xff08;Garbage-First&a…

macOS 14 Sonama - 小记

文章目录 Sonoma 官方资讯关于 Sonama 命名关于 壁纸Sonoma 官方资讯 macOS Sonoma Preview https://www.apple.com/hk/en/macos/sonoma-preview/官方视频介绍 Apple Events --> Watch the Keynote --> 00:43:13 (约14min) https://www.apple.com/hk/en/apple-events/mac…

防抖、节流、深拷贝事件总线

1 认识防抖和节流 2 underscore使用 3 防抖函数实现优化 4 节流函数实现优化 5 深拷贝函数的实现 6 事件总线工具实现 简而言之&#xff0c;防抖就是一直触发事件就一直往后拖延再执行。 节流就是一段时间就执行一次&#xff0c;不管中间你触发多少次。 防抖-认识防抖操作…

基于 NNCF 和 Optimum 面向 Intel CPU 对 Stable Diffusion 优化

基于隐空间的扩散模型 (Latent Diffusion Model)&#xff0c;是解决文本到图片生成问题上的颠覆者。Stable Diffusion 是最著名的一例&#xff0c;广泛应用在商业和工业。Stable Diffusion 的想法简单且有效: 从噪声向量开始&#xff0c;多次去噪&#xff0c;以使之在隐空间里逼…

微信加粉计数器后台开发

后台包括管理后台与代理后台两部分 管理后台 管理后台自带网络验证卡密系统,一个后台可以完成对Pc端的全部对接,可以自定义修改分组名称 分享等等代理后台 分享页 调用示例 <?php$request new HttpRequest(); $request->setUrl(http://xxxxxxx/api); $request->…
最新文章