060_Cookie/Session
会话
用户打开一个浏览器到关闭浏览器,这个过程可以称之为会话。
有状态会话
客户端再次访问服务端时,服务端知道客户端曾经来过,称之为有状态会话。
保存会话的两种技术
cookie
- 客户端技术(响应,请求)
session
- 服务端技术,利用这个技术,可以保存用户的会话信息,我们可以把信息或数据放在session中
常见场景
- 网站登录后,下次访问不需要登录
Cookie
- 服务端响应给客户端cookie
- 服务端从客户端请求中拿到cookie
Cookie[] cookies = req.getCookies();//获取cookie
cookie.getName();//获取cookie的key
cookie.getValue();//获取cookie的value
Cookie cookie = new Cookie("lastLoginTime",String.valueOf(System.currentTimeMillis()));//新建cookie
cookie.setMaxAge(24*60*60);//设置cookie有效期设置为1天
resp.addCookie(cookie);//响应给客户端一个cookie
- cookie一般会保存在本地的用户目录下的appData目录下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qing</groupId>
<artifactId>javaweb-cookie-session</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
</dependencies>
</project>
package com.qing.servlet;
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;
import java.io.PrintWriter;
import java.util.Date;
/**
* 保存用户上一次访问的时间
*/
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器告诉你,你来的时间,把这个时间封装为一个信件,下次来时,带上信件,服务器就知道你又来了
//简单解决中文乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//Cookie,服务端从客户端获取
Cookie[] cookies = req.getCookies();//这里返回数组,说明cookie可能存在多个
//判断cookie是否存在,第一次访问服务器时,不存在,cookie是由服务器给客户端的
if (cookies == null || cookies.length < 1) {
out.write("这是您第一次访问本站");
} else {
//如果存在,读取cookie,获取cookie中的值
boolean flag = true;
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if ("lastLoginTime".equals(cookie.getName())) {
flag = false;
out.write("您上一次访问本站的时间是:");
long lastLoginTime = Long.parseLong(cookie.getValue());
out.write(new Date(lastLoginTime).toLocaleString());
System.out.println(new Date(lastLoginTime).toLocaleString());
}
}
if (flag) {
out.write("这是您第一次访问本站");
}
}
//服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime",String.valueOf(System.currentTimeMillis()));
//cookie有效期设置为1天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?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"
metadata-complete="true">
<servlet>
<servlet-name>cookieDemo01</servlet-name>
<servlet-class>com.qing.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookieDemo01</servlet-name>
<url-pattern>/cookie</url-pattern>
</servlet-mapping>
</web-app>
cookie细节
- 一个cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,每个站点最多存放20个cookie
- cookie大小有限制,一般为4kb
- 浏览器存放cookie一般最多300
删除cookie
- 不设置有效期,关闭浏览器,自动失效
- 设置有效期为0
Session
什么是session
- 服务器会给每个用户(浏览器)创建一个session对象
- 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在
- 用户登录之后,整个网站都可以访问
session使用场景
- 保存登录用户的信息
- 购物车信息
- 在整个网站中经常使用的数据,我们将它保存在session中
session和cookie的区别
- cookie是把要保存的数据写给浏览器,浏览器保存(可以保存多个)
- session是把要保存的数据写的用户独占的session中,服务器保存(只保存重要的信息,减少服务器资源的浪费)
package com.qing.servlet;
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 SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//给session存数据
session.setAttribute("name","清风");
//获取session的ID
String id = session.getId();
//判断session是不是新创建的
if (session.isNew()) {
resp.getWriter().write("session创建成功,ID:" + id);
} else {
resp.getWriter().write("session已经在服务器中存在了,ID:" + id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.qing.servlet;
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 SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//从session中取数据
String name = (String) session.getAttribute("name");
System.out.println(name);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
package com.qing.servlet;
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 SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//手动注销session
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<?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"
metadata-complete="true">
<servlet>
<servlet-name>cookieDemo01</servlet-name>
<servlet-class>com.qing.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookieDemo01</servlet-name>
<url-pattern>/cookie</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sessionDemo01</servlet-name>
<servlet-class>com.qing.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sessionDemo01</servlet-name>
<url-pattern>/session1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sessionDemo02</servlet-name>
<servlet-class>com.qing.servlet.SessionDemo02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sessionDemo02</servlet-name>
<url-pattern>/session2</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>sessionDemo03</servlet-name>
<servlet-class>com.qing.servlet.SessionDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sessionDemo03</servlet-name>
<url-pattern>/session3</url-pattern>
</servlet-mapping>
<!--设置session的默认失效时间-->
<session-config>
<!--15分钟后session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
</web-app>
设置session自动过期在web.xml中
<!--设置session的默认失效时间-->
<session-config>
<!--15分钟后session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
060_Cookie/Session的更多相关文章
- session实现购物车
为实现简单的购物功能(购物车添加.账户查看.购物车商品删除.实时的购物商品数量及价格的计算显示.购物车商品数量可手动输入等),用session实现了一简单的以php语言为基础.连接MySQL数据库的购 ...
- Asp.net Core中使用Session
前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. 元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Cor ...
- 懒加载session 无法打开 no session or session was closed 解决办法(完美解决)
首先说明一下,hibernate的延迟加载特性(lazy).所谓的延迟加载就是当真正需要查询数据时才执行数据加载操作.因为hibernate当中支持实体对象,外键会与实体对象关联起来.如 ...
- 探索ASP.NET MVC5系列之~~~6.Session篇(进程外Session)
其实任何资料里面的任何知识点都无所谓,都是不重要的,重要的是学习方法,自行摸索的过程(不妥之处欢迎指正) 汇总:http://www.cnblogs.com/dunitian/p/4822808.ht ...
- Nhibernate的Session管理
参考:http://www.cnblogs.com/renrenqq/archive/2006/08/04/467688.html 但这个方法还不能解决Session缓存问题,由于创建Session需 ...
- nginx+iis+redis+Task.MainForm构建分布式架构 之 (redis存储分布式共享的session及共享session运作流程)
本次要分享的是利用windows+nginx+iis+redis+Task.MainForm组建分布式架构,上一篇分享文章制作是在windows上使用的nginx,一般正式发布的时候是在linux来配 ...
- zookeeper源码分析之六session机制
zookeeper中session意味着一个物理连接,客户端连接服务器成功之后,会发送一个连接型请求,此时就会有session 产生. session由sessionTracker产生的,sessio ...
- [转载]Cookie/Session的机制与安全
Cookie和Session是为了在无状态的HTTP协议之上维护会话状态,使得服务器可以知道当前是和哪个客户在打交道.本文来详细讨论Cookie和Session的实现机制,以及其中涉及的安全问题. 因 ...
- 修改session垃圾回收几率
<?php //修改session垃圾回收几率 ini_set('session.gc_probability','1'); ini_set('session.gc_divisor','2'); ...
随机推荐
- shit leetcode edge testcases
shit leetcode edge testcases Merge Intervals try "use strict"; /** * * @author xgqfrms * @ ...
- 智能货柜 & 技术原理 (动态视觉识别 + 重力感应)
智能货柜 & 技术原理 (动态视觉识别 + 重力感应) 智能货柜 拥有智能化.精细化运营模式的智能货柜成为代替无人货架继前进的方式. 相比无人货架来说,智能货柜的技术门槛更高,拥有 RFID. ...
- asm align 对齐数据
最大成员dword data: dd 1 db 2 align 4 dw 3 000E0010 - 01 00 00 00 000E0014 - 02 00 00 00 000E0018 - 03 0 ...
- git merge all in one
git merge all in one you can follow below steps 1. merge origin/master branch to feature branch # st ...
- Azure Functions(二)集成 Azure Blob Storage 存储文件
一,引言 上一篇文章有介绍到什么是 SeverLess ,ServerLess 都有哪些特点,以及多云环境下 ServerLess 都有哪些解决方案.在这众多解决方案中就包括 Function App ...
- Java基础语法:类型转换
由于Java是强类型语言,所以有时候在进行运算时,需要用到类型转换. 整型.常量.字符类型数据可以混合运算. 运算中,不同类型的数据先转化为同一类型,然后再进行运算. 类型转换等级有低级到高级的划分, ...
- Prism.WPF -- Prism框架使用(上)
本文参考Prism官方示例 创建Prism项目 将App.xaml中的WPF标准Application替换为PrismApplication,移除StartupUri属性: 将App.xaml.cs中 ...
- RabbitMQ-RPC版主机管理程序
一.作业需求 1.可以对指定机器异步的执行多个命令 例子: 请输入操作指令>>>:run ipconfig --host 127.0.0.0 in the call tack ...
- 死磕Spring之IoC篇 - Bean 的创建过程
该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读 Spring 版本:5.1. ...
- Java编程开发之数据图表分析模型
数据统计分析 多曲线图表分析实现 基本需求分析 假设在怪兽出没的年岁,加上年关在即,需要统计分析各个道路卡口车流量出入统计,主要从车流量和车牌地角度出发.如图所示的业务需求: 道路卡口-车流量分析: ...