首页 > 其他分享 >Cookie和Session

Cookie和Session

时间:2025-01-13 13:04:06浏览次数:3  
标签:request javax HttpServlet Session Cookie import servlet response

会话:

有状态会话:
客户端知道发起请求的是谁

无状态会话:

不知道发起请求的是谁 只知道有请求

http是无状态请求

保存会话信息的两种技术:

可以通过Cookie和Session储存会话信息

cookie:客户端技术     信心存在客户端

由服务器创建,通过响应发送给客户端,并且保存在客户浏览器的一块信息 浏览器下次向服务器发起请求时会携带这块信息并发送到服务器上

工作流程

后端中设置cookie

package com.qcby.test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SetCookie
 */
@WebServlet("/SetCookie")
public class SetCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetCookie() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		//服务器创建cookie对象
		Cookie cookie=new Cookie("username","admin");
		//设置cookie有效期 有效期小于0说明是临时的 浏览器关掉就没有了 =0则是删除这个cookie
		cookie.setMaxAge(60*60);
		//将cookie相应给客户端
		response.addCookie(cookie);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 后端中读取cookie

package com.qcby.test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GetCookie
 */
@WebServlet("/GetCookie")
public class GetCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetCookie() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		Cookie[] cookies=request.getCookies();
		for(int i=0;i<cookies.length;i++)
		{
			System.out.println(cookies[i].getName()+"-->"+cookies[i].getValue());
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 js中创建cookie

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	document.cookie="password=123456;max-age="+30*60;
	var getCookie=function(name){
		var cookies=document.cookie.split(";");//以";"做分割
		for(var i=0;i<cookies.length;i++){
			if(cookies[i].trim().indexOf(name)==0)//子串中是否包含name
				{
				return cookies[i].trim().substring(name.length+1)
				}
		}
		return ""
	}
	
	console.log(getCookie("password"))
</script>
</head>
<body>

</body>
</html>

使用js的cookie插件创建cookie

jQuery Cookie 插件 | 菜鸟教程 去这下插件 有用法解释

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.staticfile.org/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
	$.cookie("color","pink")
</script>
</head>
<body>

</body>
</html>

cookie的优缺点

优点:

可设置到期规则  重复访问时不需要再次登录

包含简单的键值对 数据持久

缺点:
大小受限制 

浏览器可以设置cookie禁用 

cookie可被篡改 不安全

session:服务端技术 信息存在服务端 只能在后端中进行

为每次会话创建一个会话对象 也就是session对象 存储和取数据都在这个对象中

工作流程:

创建session

package com.qcby.test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SetSession
 */
@WebServlet("/SetSession")
public class SetSession extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetSession() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		HttpSession session=request.getSession();
		
		session.setAttribute("account", "admin");
		session.setAttribute("password", "123456");
		session.setAttribute("demo", "777");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 获取

package com.qcby.test;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class GetSession
 */
@WebServlet("/GetSession")
public class GetSession extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetSession() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		HttpSession session=request.getSession();
		System.out.println(session.getId());//获取jsessionid
		System.out.println(session.getAttribute("account"));
		System.out.println(session.getAttribute("password"));
		System.out.println(session.getAttribute("demo"));
		
		session.removeAttribute("demo");//删除demo
		session.invalidate();//销毁session 关掉浏览器也可以实现 jsessionid就会改变
		session.setMaxInactiveInterval(60*60);//设置有效期
		//session生命周期
		//第一次使用到session的请求创建session
		//浏览器关闭或者服务器关闭或者手动销毁或者到期超时失效
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

标签:request,javax,HttpServlet,Session,Cookie,import,servlet,response
From: https://blog.csdn.net/2403_87729201/article/details/145110676

相关文章

  • 请说说在Angular中怎样设置、获取和清除cookie?
    在Angular中,原生的Angular库并不直接提供设置、获取和清除cookie的功能。但是,你可以使用一些第三方的库,如ngx-cookie-service,或者通过JavaScript的原生方法来操作cookie。使用JavaScript原生方法设置Cookie你可以使用document.cookie来设置cookie,如下所示:document.cookie=......
  • 设置cookie
    设置一个cookie,使网站能识别来自同一个Web浏览器的后续请求boolsetcookie(string$name[,string$value=""[,int$expires=0[,string$path=""[,string$domain=""[,bool$secure=false[,bool$httponly=false]]]]]]])参数说明:1、$name(必......
  • 认识Token和Cookie
    认识Token和Cookie1、token和cookie有什么区别?​ 1.1存储位置及方式:Cookie是浏览器用来存储本地信息的文件,有一定的存储限制,而Token是由服务器按一定算法生成的密令,可以由前端指定存放到localStorage、sessionStorage或cookie中。​ 1.2功能特性:每次浏览器发起HTTP请求都......
  • 《深入理解Mybatis原理》MyBatis的sqlSession执行流程
    sqlSessionFactory与SqlSession正如其名,Sqlsession对应着一次数据库会话。由于数据库会话不是永久的,因此Sqlsession的生命周期也不应该是永久的,相反,在你每次访问数据库时都需要创建它(当然并不是说在Sqlsession里只能执行一次sql,你可以执行多次,当一旦关闭了Sqlsession就需要重新......
  • 请问sessionStrorage多久会过期?
    sessionStorage的过期时间并不是基于一个固定的时长,而是与浏览器窗口或标签页的生命周期紧密相关。以下是对sessionStorage过期时间的详细解释:生命周期:sessionStorage的有效期是和存储数据脚本所在的最顶层的窗口或者是浏览器标签页一样的。一旦这个窗口或者标签页被永久关闭(即......
  • 浏览器本地存储 WebStorage包括localstorage sessionstorage
    一、概念浏览器端通过sessionstorage和localstorage属性来实现本地存储 二、相关API//设置,keyvalue,key若存在,则则更新value,value为字符串,需要使用JSONlocalStorage.setItem('msg','Hello')sessionStorage.setItem('msg','Hello')//获取value,根据key,value是字符串,......
  • 三个域对象->Request域、Session域、Application域
    Servlet中的三个域对象请求域:request会话域:session应用域:application三个域都有以下三个方法://向域中存储数据voidsetAttribute(Stringname,Objectobj);​//从域中读取数据ObjectgetAttribute(Stringname);​//删除域中的数据voidremoveAttribute(Strin......
  • 【PHP编程】PHP Session 设置
    “在Web开发中,Session管理是非常重要的一个环节。通过Session,我们可以跟踪用户的状态,存储用户特定的信息,以及执行其他与用户会话相关的操作。”PHP提供了强大的Session功能,使得开发者可以轻松地设置和管理Session。本篇文章将深入探讨如何在PHP中设置Session,并通过丰富的代码示......
  • 新窗口打开同样的站点会共用sessionStrorage吗?
    在前端开发中,关于新窗口打开同样的站点是否会共用sessionStorage的问题,答案是否定的。具体来说,原因如下:sessionStorage的定义与特性sessionStorage是WebStorageAPI的一部分,提供了一种在浏览器会话期间存储数据的机制。它允许你访问一个对应当前源的sessionStorage对象。与loca......
  • cookie构成部分有哪些
    名称(Name)定义:这是cookie的标识符,用于在后续的操作中识别特定的cookie。名称必须是唯一的,在同一个域名下不能有两个名称相同的cookie。例如,一个用于存储用户登录状态的cookie可以命名为“login_status”。规则:名称是一个字符串,其长度和内容受到一定限制。通常,名称可以包含字母......