博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
cookie 和session
阅读量:5796 次
发布时间:2019-06-18

本文共 11204 字,大约阅读时间需要 37 分钟。

hot3.png

package com.atguigu.demo;import java.util.UUID;public class Demo {	/**	 * * Cookie	  		* 简介	  			* Cookie实际上就是服务器保存在浏览器上的一段信息,主要用于区分不同的用户。	  		* Cookie运行原理	  			* 请求	  			* 服务器创建一个Cookie对象,该Cookie对象携带用户信息,服务器发送(响应)给客户端	  			* 以后客户端再发送请求时,会携带该Cookie对象。	  			* 服务器会根据该Cookie对象(及信息),区分不同用户。  		  		* Cookie	  			* 创建	  				* Cookie cookie = new Cookie(String name,String value); 	  				* response.addCookie(cookie);	  			* 获取	  				* Cookie[] cookies = request.getCookies(); 	  				* cookie.getName()|getValue()				* 修改					* 覆盖式修改						* Cookie cookie = new Cookie("同名","新值");						* response.addCookie(cookie);					* 直接修改						* Cookie[] cookies = request.getCookies();							* 找到指定的Cookie						* cookie.setValue("新值");			* Cookie的键值问题				* name不可以为中文,value可以为中文,需要指定字符集问题,所有建议使用英文。	  		* Cookie有效性	  			* 默认为会话级别,与浏览器有关(关闭浏览器或换一个浏览器失效)	  			* 持久化	  				* setMaxAge(ss:秒);	  					* ss>0:在ss秒后失效	  					* ss=0:立即失效	  					* ss<0:默认会话级别	  			* 注意:持久化Cookie,该Cookie不是会话级别。	  		* Cookie有效路径	  			* 默认有效路径:当前项目路径	  			* setPath():一般设置有效路径,都是基于当前项目下的路径进行设置。	  				* 如:cookie.setPath(request.getContextPath()+"/a");	  		* Cookie应用	  			* 记住密码	  		* Cookie缺陷	  			* Cookie的value为String型,不灵活。	  			* Cookie存放在浏览器中,不安全。	  			* Cookie过多,会浪费流量。	   * Session	   		* 简介	   			* 类型:HttpSession	   		* Session工作原理	   			* 请求	   			* 服务器创建Session,同时创建一个特殊的Cookie,该Cookie的key为固定值:JSESSIONID,	   			   value为session的id。	   			* 服务器将该Cookie对象发送(响应)给客户端	   			* 以后客户端再请求时,会携带该Cookie对象。	   			* 服务器会根据Cookie的value,找到相应的Session,从而区分不同的给用户。	   		* Session获取  	   			* html(Servlet):request.getSession()	   			* jsp:直接获取(session是jsp中的隐含对象)	  		* Session有效性	  			* 默认有效性:当前会话(因为特殊的Cookie是会话级别)	  			* 持久化Session	  				* 持久化特殊Cookie 	  				* Session存活时间	  					* 默认存活时间为30分。	  					* 设置session的非活动时间	  						* web.xml中	  						 	
30分钟
* session.setMaxInactiveInterval(ss秒); * ss>0:在ss秒后失效 * ss<=0:永不失效(Tomcat>=7) * session立即失效 * session.invalidate(); * Session钝化与活化 * 钝化:将session对象及session对象中的数据,一同从内存中序列化到硬盘的过程称之为钝化。 * 时机:服务器关闭时触发 * 活化:将session对象及session对象中的数据,一同从硬盘反序列化到内存的过程称之为活化。 * 时机:服务器重启时触发 * 表单重复提交问题 * 转发,F5 * 提交后,网速慢,连续点击提交按钮 * 提交后,点击回退按钮,继续提交 * 提交-Servlet-响应 * 思路:在Servlet中干预提交,第一次提交,以后不提交 1. 使用UUID,作为Token。将Token存放到session域和隐藏域中。 * UUID:是一个全球唯一的32为的16进制的随机数。 2. 提交,判断变量是否为初始值 true:提交,移除session域中的Token(UUID)。 false:不提交 */ public static void main(String[] args) { String uuid = UUID.randomUUID().toString().replace("-",""); System.out.println(uuid); } }
package com.atguigu.servlet.cookie;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class CreateCookieServlet */public class CreateCookieServlet extends HttpServlet {	private static final long serialVersionUID = 1L;       	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		//创建Cookie对象,并携带用户信息		Cookie cookieName = new Cookie("stuName", "zhangsan");		//响应给客户端		response.addCookie(cookieName);			}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doGet(request, response);	}}
package com.atguigu.servlet.cookie;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class GetCookieServlet */public class GetCookieServlet extends HttpServlet {	private static final long serialVersionUID = 1L;       	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		//获取Cookie		Cookie[] cookies = request.getCookies();				for (Cookie cookie : cookies) {			System.out.print("cookieName:"+cookie.getName());			System.out.println("cookieValue:"+cookie.getValue());		}			}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doGet(request, response);	}}
package com.atguigu.servlet.cookie;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class ChiCookieServlet */public class ChiCookieServlet extends HttpServlet {	private static final long serialVersionUID = 1L;       	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		Cookie cookie = new Cookie("stuAge", "18");		//持久化//		cookie.setMaxAge(-1);		//有效路径		cookie.setPath(request.getContextPath()+"/a");		response.addCookie(cookie);	}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doGet(request, response);	}}
package com.atguigu.servlet.cookie;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class UserServlet */public class UserServlet extends HttpServlet {	private static final long serialVersionUID = 1L;       	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		String username = request.getParameter("username");		String password = request.getParameter("password");		String rp = request.getParameter("rp");		if(rp != null) {			//将数据存放Cookie中			Cookie cookieName = new Cookie("username", username);			Cookie cookiePwd = new Cookie("cookiePwd", password);			//将Cookie持久化			cookieName.setMaxAge(60);	//7天=60*60*24*7			cookiePwd.setMaxAge(60);			//将Cookie响应给浏览器			response.addCookie(cookieName);			response.addCookie(cookiePwd);		}		//跳转	}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doGet(request, response);	}}
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Insert title here

CookieDemo

创建Cookie对象
获取Cookie对象
修改Cookie对象
持久化Cookie对象
package com.atguigu.servlet.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class ShiSessionServlet */public class ShiSessionServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		HttpSession session = request.getSession();		//设置session失效		session.invalidate();	}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doGet(request, response);	}}
package com.atguigu.servlet.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class GetSessionServlet */public class GetSessionServlet extends HttpServlet {	private static final long serialVersionUID = 1L;       	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		HttpSession session = request.getSession();		System.out.println(session.getId());	}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doGet(request, response);	}}
package com.atguigu.servlet.session;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;/** * Servlet implementation class ReSubServlet */public class ReSubServlet extends HttpServlet {	private static final long serialVersionUID = 1L;       	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		HttpSession session = request.getSession();		//分别取session域和隐藏域中的uuid值		String uuid2 = request.getParameter("uuid2");		Object uuid = session.getAttribute("uuid");		//判断是否相等,		if(uuid != null && uuid.toString().equals(uuid2)) {			//相等:提交,移除session域中的token			System.out.println("提交啦!!!哈哈");			session.removeAttribute("uuid");		}				System.out.println("end!");			}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doGet(request, response);	}}
package com.atguigu.servlet.session;import java.io.IOException;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 javax.servlet.http.HttpSession;import com.atguigu.bean.Student;/** * Servlet implementation class ChiSessionServlet */public class ChiSessionServlet extends HttpServlet {	private static final long serialVersionUID = 1L;       	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		//持久化Session-》持久化特殊的Cookie		Cookie[] cookies = request.getCookies();		for (Cookie cookie : cookies) {			if("JSESSIONID".equals(cookie.getName())) {				cookie.setMaxAge(600);				response.addCookie(cookie);				break;			}		}		//设置session的非活动时间		HttpSession session = request.getSession();		session.setMaxInactiveInterval(600);				session.setAttribute("stu", new Student("zhangsan"));			}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		doGet(request, response);	}}
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Insert title here sessionId:<%=session.getId() %>
获取Session
持久化Session
设置Session立即失效
student:<%=session.getAttribute("stu") %>
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
尚硅谷会员登录页面
记住密码:
<%@page import="java.util.UUID"%><%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
尚硅谷会员登录页面 <% String uuid = UUID.randomUUID().toString().replace("-", ""); session.setAttribute("uuid", uuid); %>

 

转载于:https://my.oschina.net/architectliuyuanyuan/blog/3057916

你可能感兴趣的文章
Java重写equals方法和hashCode方法
查看>>
Spark API编程动手实战-07-join操作深入实战
查看>>
EasyUI基础入门之Easyloader(载入器)
查看>>
Spring ’14 Wave Update: Installing Dynamics CRM on Tablets for Windows 8.1
查看>>
MySQL 备份与恢复
查看>>
吃午饭前,按书上的代码写会儿--Hunt the Wumpus第一个版本
查看>>
TEST
查看>>
PAT A1037
查看>>
ReactiveSwift源码解析(三) Signal代码的基本实现
查看>>
(六)Oracle学习笔记—— 约束
查看>>
[Oracle]如何在Oracle中设置Event
查看>>
top.location.href和localtion.href有什么不同
查看>>
02-创建hibernate工程
查看>>
information_schema系列五(表,触发器,视图,存储过程和函数)
查看>>
Scrum之 Sprint计划会议
查看>>
svn命令在linux下的使用
查看>>
Gradle之module间依赖版本同步
查看>>
java springcloud版b2b2c社交电商spring cloud分布式微服务(十五)Springboot整合RabbitMQ...
查看>>
SpringCloud使用Prometheus监控(基于Eureka)
查看>>
10g手动创建数据库
查看>>