当前位置: 首页 > news >正文

javaEE-03-cookie与session

文章目录

  • Cookie
    • 创建Cookie
    • 获取Cookie
    • 更新Cookie
    • Cookie 生命控制
    • Cookie 有效路径
  • Session 会话
    • 创建和获取session
    • Session 域数据的存取
    • Session 生命周期控制
      • 浏览器和 Session 之间关联

Cookie

Cookie 是服务器通知客户端保存键值对的一种技术,客户端有了 Cookie 后,每次请求都发送给服务器并且每个 Cookie 的大小不能超过 4kb。

创建Cookie

  1. 创建一个新的servlet程序CookieServlet
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 CookieServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html;charset=utf-8");//1 创建Cookie 对象Cookie cookie = new Cookie("username", "root");//2 通知客户端保存Cookieresp.addCookie(cookie);//1 创建Cookie 对象Cookie cookie1 = new Cookie("password", "123456");//2 通知客户端保存Cookieresp.addCookie(cookie1);resp.getWriter().write("Cookie 创建成功");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
  1. 增加新的映射文件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>CookieServlet</servlet-class></servlet><servlet-mapping><servlet-name>CookieServlet</servlet-name><url-pattern>/createCookie</url-pattern></servlet-mapping>
</web-app>
  1. 启动服务器,测试cookie是否创建成功,http://localhost:8080/javaee_tomcat_war_exploded/createCookie
    在这里插入图片描述
    按F12,或者鼠标右击检查,选择应用程序,点开Cookie,查看到对应信息
    在这里插入图片描述

获取Cookie

  1. 创建一个工具类用来获取Cookie信息CookieUtils
import javax.servlet.http.Cookie;public class CookieUtils {/*** 查找指定名称的Cookie 对象** @param name* @param cookies* @return*/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;}}
  1. 创建一个新的servlet用来获取到Cookie信息
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 getCookieServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html;charset=utf-8");Cookie[] cookies = req.getCookies();for (Cookie cookie : cookies) {// getName 方法返回Cookie 的key(名)// getValue 方法返回Cookie 的value 值resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");}Cookie mycookie = CookieUtils.findCookie("username", cookies);// 如果不等于null,说明赋过值,也就是找到了需要的Cookieif (mycookie != null) {resp.getWriter().write("找到了需要的 Cookie");}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
  1. 新增对应的映射文件信息
<?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>getCookieServlet</servlet-name><servlet-class>getCookieServlet</servlet-class></servlet><servlet-mapping><servlet-name>getCookieServlet</servlet-name><url-pattern>/getCookie</url-pattern></servlet-mapping>
</web-app>
  1. 启动项目进行访问。
    http://localhost:8080/javaee_tomcat_war_exploded/getCookie
    在这里插入图片描述
    这里我们直接获取到了cookie信息,这是因为我们之前的程序中存放了对应的cookie信息,如果我们换一个浏览器进行访问就访问不到之前的cookie信息了,这时我们可以重新调用一下http://localhost:8080/javaee_tomcat_war_exploded/createCookie这个请求,再获取cookie。

更新Cookie

更新cookie有俩种方法:

  • 先创建一个要修改的同名(指的就是 key)的 Cookie 对象,在构造器,同时赋于新的 Cookie 值,最后调用 response.addCookie( Cookie );
  • 先查找到需要修改的 Cookie 对象,调用 setValue()方法赋于新的 Cookie 值,调用 response.addCookie()通知客户端保存修改。

Cookie 生命控制

管理 Cookie 什么时候被销毁(删除)
通过Cookie对象中的setMaxAge()来控制Cookie的声明周期。

  • 正数,表示在指定的秒数后过期, cookie.setMaxAge(60 * 60);表示一小时后cookie失效
  • 负数,表示浏览器一关,Cookie 就会被删除(默认值是-1),cookie.setMaxAge(-1);表示浏览器一关cookie就会失效
  • 零,表示马上删除 Cookie,cookie.setMaxAge(-1);表示cookie马上就会失效。

Cookie 有效路径

Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器。哪些不发。

  • cookie.setPath( req.getContextPath() + "/abc" ); 表示工程路径/abc路径下面的可以获取到cookie信息。
    

Session 会话

Session 就是一个接口(HttpSession),作为一个会话,它是用来维护一个客户端和服务器之间关联的一种技术。每个客户端都有自己的一个 Session 会话。

创建和获取session

通过HttpServletRequest中的getSession()方法来创建一个session对象,之后使用该方法都是获取到之前创建的session对象。

  • isNew(): 判断到底是不是刚创建出来的(新的)
  • getId(): 得到 Session 的会话 id 值。

Session 域数据的存取

  1. 定义俩个servlet程序,一个用来存入数据,一个用来取出数据

SessionServlet类

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;public class SessionServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession();session.setAttribute("username","xiaoming");session.setAttribute("password","123456");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}

getSessionServlet类

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;public class getSessionServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession();String username = (String) session.getAttribute("username");String password = (String) session.getAttribute("password");System.out.println("用户名:" + username + ",密码:" + password);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
  1. 创建对应的映射文件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>SessionServlet</servlet-name><servlet-class>SessionServlet</servlet-class></servlet><servlet-mapping><servlet-name>SessionServlet</servlet-name><url-pattern>/createSession</url-pattern></servlet-mapping><servlet><servlet-name>getSessionServlet</servlet-name><servlet-class>getSessionServlet</servlet-class></servlet><servlet-mapping><servlet-name>getSessionServlet</servlet-name><url-pattern>/getSession</url-pattern></servlet-mapping>
</web-app>
  1. 启动服务进行测试,先输入这个网站http://localhost:8080/javaee_tomcat_war_exploded/createSession进行数据的请求,再输入http://localhost:8080/javaee_tomcat_war_exploded/getSession进行数据获取。

在这里插入图片描述

Session 生命周期控制

  1. 通过HttpSession对象中的setMaxInactiveInterval()来设置 Session 的超时时间(以秒为单位)。
  • 值为正数的时候: 设定 Session 的超时时长。
  • 值为负数的时候: 永不超时
  1. 通过getMaxInactiveInterval()方法来获取 Session 的超时时间
  2. 通过invalidate()来让当前Session会话马上失效
  3. Session 默认的超时时间长为 30 分钟。这个是tomcat中的默认配置。这个设置可以进行修改
<!--表示当前web 工程。创建出来的所有Session 默认是20 分钟超时时长-->
<session-config><session-timeout>20</session-timeout>
</session-config>

浏览器和 Session 之间关联

Session 技术,底层其实是基于 Cookie 技术来实现的。

  1. 当浏览器没有任何Cookie信息的时候,发请求到tomcat服务器时调用了HttpServletRequest对象的getSession()方法,这时服务器会创建一个Cookie对象,这个Cookie对象的key为JSESSIONID,值为新创建出来的Sessino的id值。
  2. 通过响应将该值传递给客户端,之后客户端每次请求的时候就会将id以Cookie的形式发送给服务器端。
  3. 服务器再获取HttpSession对象的时候就会通过Cookie中的id值来找到自己之前创建的Seesion对象。

欢迎java热爱者了解文章,作者将会持续更新中,期待各位友友的关注和收藏,另外对编程感兴趣的友友们可以加以下群共同学习。群号:127871664

相关文章:

javaEE-03-cookie与session

文章目录 Cookie创建Cookie获取Cookie更新CookieCookie 生命控制Cookie 有效路径 Session 会话创建和获取sessionSession 域数据的存取Session 生命周期控制浏览器和 Session 之间关联 Cookie Cookie 是服务器通知客户端保存键值对的一种技术,客户端有了 Cookie 后&#xff0c…...

EtherNet/IP转Profinet协议网关(经典配置案例)

怎么样才能把EtherNet/IP和Profinet网络连接起来呢?这几天有几个朋友问到了这个问题&#xff0c;作者在这里统一为大家详细说明一下。其实有一个设备可以很轻松地解决这个问题&#xff0c;名为JM-PN-EIP&#xff0c;下面是详细介绍。 一&#xff0c;设备主要功能 1、捷米特J…...

华为云依赖引入错误

问题&#xff1a;记录一次项目加在华为云依赖错误&#xff0c;如下&#xff1a; 错误信息&#xff1a;Could not find artifact com.huawei.storage:esdk-obs-java:pom:3.1.2.1 in bintray-qcloud-maven-repo (https://dl.bintray.com/qcloud/maven-repo/) 找到本地仓库&#…...

【Ubuntu】Ubuntu 配置镜像源(ARM)

【Ubuntu】Ubuntu 配置镜像源&#xff08;ARM&#xff09; 零、起因 最近在QEMU中安装了个ubuntu-24.04-live-server-arm64&#xff0c;默认是国外的软件源&#xff0c;很慢&#xff0c;故替换到国内。 壹、替换 源地址&#xff08;清华源&#xff09; https://mirror.tun…...

速腾聚创激光雷达复现FAST-LIO

目录 1.软件环境 2.测试执行 3.代码学习 3.1.找主节点代码文件 3.2.整体流程结构 3.3.具体函数理解 记录复现FAST-LIO算法的过程和&#xff0c;代码梳理和理解 1.软件环境 Windows 10(64bits) VMware 16 Pro Ubuntu 20.04 ROS Noetic FAST-LIO的简化版、注释版。感谢…...

k8s核心知识总结

写在前面 时间一下子到了7月份尾&#xff1b;整个7月份都乱糟糟的&#xff0c;不管怎么样&#xff0c;日子还是得过啊&#xff0c; 1、7月份核心了解个关于k8s&#xff0c;iceberg等相关技术&#xff0c;了解了相关的基础逻辑&#xff0c;虽然和数开主线有点偏&#xff0c;但是…...

语言模型及数据集

一、定义 1、语言模型的目标是估计序列的联合概率&#xff0c;一个理想的语言模型就能够基于模型本身生成自然文本。 2、对一个文档&#xff08;词元&#xff09;序列进行建模&#xff0c; 假设在单词级别对文本数据进行词元化。 3、计数建模 &#xff08;1&#xff09;其中…...

linux如何卸载python3.5

卸载&#xff1a; 1、卸载python3.5 sudo apt-get remove python3.5 2、卸载python3.5及其依赖 sudo apt-get remove --auto-remove python3.5 3、清除python3.5 sudo apt-get purge python3.5 或者 sudo apt-get purge --auto-remove python3.5...

【BUG】已解决:TypeError: expected string or bytes-like object

TypeError: expected string or bytes-like object 目录 TypeError: expected string or bytes-like object 【常见模块错误】 【解决方案】 常见原因及解决方法 示例代码 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&#xff0c;我是博主英杰…...

在linux上面用drissionpage自动化遇到反爬?

目录 一、反爬内容1、案例12、案例2 二、后来发现的问题解决 一、反爬内容 1、案例1 反爬的响应文本返回如下&#xff1a;爬虫均能精准识别,测试链接:https://ziyuan.baidu.com/crawltools/index)非正常爬虫访问时:返回的压缩报文内容无法直接识别,可一定程度上保护站点信息安…...

vue3大事件管理系统 === 首页 layout 文章分类页面 -

目录 首页 layout 架子 [element-plus 菜单] 基本架子拆解 登录访问拦截 用户基本信息获取&渲染 退出功能 [element-plus 确认框] 文章分类页面 - [element-plus 表格] 基本架子 - PageContainer 文章分类渲染 封装API - 请求获取表格数据 el-table 表格动态渲染 …...

堆的基本实现

一、堆的概念 在提出堆的概念之前&#xff0c;首先要了解二叉树的基本概念 一颗二叉树是节点的有限集合&#xff0c;该集合&#xff1a; 1、或者为空&#xff1b; 2、或者由一个根节点加上两颗分别称为左子树和右子树的两颗子树构成&#xff1b; 堆就是一颗完全二叉树&…...

Ubuntu上编译多个版本的frida

准备工作 Ubuntu20(WSL) 略 安装依赖 sudo apt update sudo apt-get install build-essential git lib32stdc-9-dev libc6-dev-i386 -y nodejs 去官网[1]下载nodejs&#xff0c;版本的话我就选的20.15.1&#xff1a; tar -xf node-v20.15.1-linux-x64.tar.xz 下载源码 …...

概率论三大分布

目录 基本概念 卡方分布&#xff08;χ分布&#xff09;&#xff1a; t分布&#xff1a; F分布&#xff1a; 延伸 卡方分布在哪些具体情况下最适合用于数据分析&#xff1f; t分布在大样本情况下的表现与正态分布相比如何&#xff1f; F分布在进行方差比较时与t分布的区…...

Spring系统学习-基于XML的声明式事务

基本概念 在Spring框架中&#xff0c;基于XML的事务管理是一种通过XML配置文件来管理事务的方式。Spring提供了强大的事务管理功能&#xff0c;可以与多种持久化技术&#xff08;如JDBC、Hibernate、JPA等&#xff09;结合使用。以下是如何在Spring中使用基于XML的事务管理的基…...

iOS中的MVVM设计模式

目录 前言 一、MVVM简介 二、MVVM的核心思想 三、MVVM的优势 四、MVVM在iOS中的实现 1. 创建Model 2. 创建ViewModel 3. 创建View 4. 主入口 总结 前言 随着iOS开发的发展&#xff0c;构建可维护和可扩展的代码架构变得至关重要。Model-View-ViewModel (MVVM) 是一种…...

ES中的数据类型学习之ARRAY

Arrays | Elasticsearch Guide [7.17] | Elastic 中文翻译 &#xff1a;Array Elasticsearch 5.4 中文文档 看云 Arrays In Elasticsearch, there is no dedicated array data type. Any field can contain zero or more values by default, however, all values in the a…...

vue网络请求

post网络请求 import axios from axios import {ElMessage, ElLoading} from "element-plus" import { nextTick } from "vue" import JSONbig from json-bigint import { userToken } from "/constants/Constant.js";const defaultConfig {bas…...

几何光学基本原理——费马原理和射线方程

在几何光学中&#xff0c;射线方程用于描述光在折射率不均匀的介质中传播的路径。折射率的变化会导致射线发生弯曲&#xff0c;射线方程正是用于计算这种弯曲路径的。 几何光学的基本原理 几何光学假设光在介质中沿直线传播&#xff0c;但在折射率变化的介质中&#xff0c;光的…...

OpenCV车牌识别技术详解

第一部分&#xff1a;图像预处理 车牌识别&#xff08;License Plate Recognition&#xff0c;LPR&#xff09;是计算机视觉领域的一个重要应用&#xff0c;它涉及到图像处理、模式识别等多个方面。OpenCV作为一个强大的计算机视觉库&#xff0c;提供了丰富的车牌识别相关功能…...

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …...

JavaSec-RCE

简介 RCE(Remote Code Execution)&#xff0c;可以分为:命令注入(Command Injection)、代码注入(Code Injection) 代码注入 1.漏洞场景&#xff1a;Groovy代码注入 Groovy是一种基于JVM的动态语言&#xff0c;语法简洁&#xff0c;支持闭包、动态类型和Java互操作性&#xff0c…...

智慧医疗能源事业线深度画像分析(上)

引言 医疗行业作为现代社会的关键基础设施,其能源消耗与环境影响正日益受到关注。随着全球"双碳"目标的推进和可持续发展理念的深入,智慧医疗能源事业线应运而生,致力于通过创新技术与管理方案,重构医疗领域的能源使用模式。这一事业线融合了能源管理、可持续发…...

JavaScript 中的 ES|QL:利用 Apache Arrow 工具

作者&#xff1a;来自 Elastic Jeffrey Rengifo 学习如何将 ES|QL 与 JavaScript 的 Apache Arrow 客户端工具一起使用。 想获得 Elastic 认证吗&#xff1f;了解下一期 Elasticsearch Engineer 培训的时间吧&#xff01; Elasticsearch 拥有众多新功能&#xff0c;助你为自己…...

3.3.1_1 检错编码(奇偶校验码)

从这节课开始&#xff0c;我们会探讨数据链路层的差错控制功能&#xff0c;差错控制功能的主要目标是要发现并且解决一个帧内部的位错误&#xff0c;我们需要使用特殊的编码技术去发现帧内部的位错误&#xff0c;当我们发现位错误之后&#xff0c;通常来说有两种解决方案。第一…...

【位运算】消失的两个数字(hard)

消失的两个数字&#xff08;hard&#xff09; 题⽬描述&#xff1a;解法&#xff08;位运算&#xff09;&#xff1a;Java 算法代码&#xff1a;更简便代码 题⽬链接&#xff1a;⾯试题 17.19. 消失的两个数字 题⽬描述&#xff1a; 给定⼀个数组&#xff0c;包含从 1 到 N 所有…...

定时器任务——若依源码分析

分析util包下面的工具类schedule utils&#xff1a; ScheduleUtils 是若依中用于与 Quartz 框架交互的工具类&#xff0c;封装了定时任务的 创建、更新、暂停、删除等核心逻辑。 createScheduleJob createScheduleJob 用于将任务注册到 Quartz&#xff0c;先构建任务的 JobD…...

跨链模式:多链互操作架构与性能扩展方案

跨链模式&#xff1a;多链互操作架构与性能扩展方案 ——构建下一代区块链互联网的技术基石 一、跨链架构的核心范式演进 1. 分层协议栈&#xff1a;模块化解耦设计 现代跨链系统采用分层协议栈实现灵活扩展&#xff08;H2Cross架构&#xff09;&#xff1a; 适配层&#xf…...

2025盘古石杯决赛【手机取证】

前言 第三届盘古石杯国际电子数据取证大赛决赛 最后一题没有解出来&#xff0c;实在找不到&#xff0c;希望有大佬教一下我。 还有就会议时间&#xff0c;我感觉不是图片时间&#xff0c;因为在电脑看到是其他时间用老会议系统开的会。 手机取证 1、分析鸿蒙手机检材&#x…...

【Oracle】分区表

个人主页&#xff1a;Guiat 归属专栏&#xff1a;Oracle 文章目录 1. 分区表基础概述1.1 分区表的概念与优势1.2 分区类型概览1.3 分区表的工作原理 2. 范围分区 (RANGE Partitioning)2.1 基础范围分区2.1.1 按日期范围分区2.1.2 按数值范围分区 2.2 间隔分区 (INTERVAL Partit…...