博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Cookie、Session
阅读量:2112 次
发布时间:2019-04-29

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

一、Cookie

1、什么是Cookie

① Cookie是服务器通知客户端保存键值对的一种技术

② Cookie是Servlet发送到Web浏览器的少量信息,这些信息由浏览器保存,然后发送回服务器。Cookie的值可以唯一地表示客户端

③ 客户端有了Cookie后,每次请求都发送给服务器。

④ 每个Cookie的大小不能超过4Kb。

2、如何创建Cookie

在这里插入图片描述

BaseServlet程序如下:

public abstract class BaseServlet extends HttpServlet {
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决post请求中文乱码问题 //一定要在获取请求参数之前调用才有效 request.setCharacterEncoding("UTF-8"); //解决响应中文乱码问题 response.setContentType("text/html;charset=UTF-8"); String action = request.getParameter("action"); try {
// 获取action业务鉴别字符串,获取相应的业务方法反射现象 Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class); // 调用目标业务方法 method.invoke(this,request,response); } catch (Exception e) {
e.printStackTrace(); } }}

CookieServlet程序如下:

public class CookieServlet extends BaseServlet{
protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、创建Cookie对象 Cookie cookie = new Cookie("key1", "value1"); //2、通知客户端保存Cookie response.addCookie(cookie); response.getWriter().write("Cookie创建成功"); }}

3、服务器如何获取Cookie

服务器获取客户端的Cookie只需要一行代码:request.getCookie():Cookie[]

工具类CookieUtils工具类代码如下:

public class CookieUtils {
/* * 查找指定名称的Cookie对象 * */ 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; }}

获取想要的Cookie代码如下:

public class CookieServlet extends BaseServlet{
protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies(); for (Cookie cookie:cookies){
//getName方法返回Cookie的key(名) response.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "]
" ); } // 使用自定义工具类 Cookie iWantCookie= CookieUtils.findCookie("key1",cookies); // 自己查找 /*for (Cookie cookie:cookies){ if ("key1".equals(cookie.getName())){ iWantCookie=cookie; break; } }*/ // 如果不等于null,说明赋过值,也就是找到了需要的Cookie if (iWantCookie!=null){
response.getWriter().write("找到了需要的Cookie"); } }}

4、Cookie值得修改

方案一

① 先创建一个要修改得同名的Cookie对象② 在构造器,同时赋予新的Cookie值③ 调用response.addCookie(Cookie)通知客户端保存修改
protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 方案一: //① 先创建一个要修改得同名的Cookie对象 //② 在构造器,同时赋予新的Cookie值 Cookie cookie = new Cookie("key1", "newValue1"); //③ 调用response.addCookie(Cookie) -通知客户端保存修改 response.addCookie(cookie); response.getWriter().write("key1的Cookie已经修改好"); }

方案二

① 先查找到需要修改的Cookie对象② 调用setValue()方法赋于新的Cookie值③ 调用response.addCookie(Cookie)通知客户端保存修改
protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//方案二: //① 先查找到需要修改的Cookie对象 Cookie cookie = CookieUtils.findCookie("key2", request.getCookies()); if (cookie!=null){
//② 调用setValue()方法赋于新的Cookie值 cookie.setValue("newValue2"); } //③ 调用response.addCookie(Cookie)通知客户端保存修改 response.addCookie(cookie); response.getWriter().write("key2的Cookie已经修改好"); }

对于Version 0 cookie,值不应包含空格、方括号、圆括号、等号、逗号、双引号、斜杠、问号、at符号、冒号和分号。空值在所有浏览器上的行为不一定相同。如过使用二进制值或中文,则可能需要使用BASE64编码

5、Cookie生命控制 - - - setMaxAge()

Cookie的生命控制是指如何管理Cookie的销毁(删除)

setMaxAge()	正数,表示在指定的秒数后过期	负数,表示浏览器一关,Cookie就会被删除(默认值是-1)	零,表示马上删除Cookie
// 默认-1,表示浏览器一关,Cookie被删除    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("defaultLife", "defaultLife"); cookie.setMaxAge(-1); //设置存活时间 response.addCookie(cookie); } //设置0,立即删除当前Cookie protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//先找到要删除的Cookie对象 Cookie cookie = CookieUtils.findCookie("key3", request.getCookies()); if (cookie!=null){
//调用setMaxAge(0); cookie.setMaxAge(0); //表示马上删除,不需要等待浏览器关闭 //调用response.addCookie(cookie) response.addCookie(cookie); response.getWriter().write("key3的Cookie已经被删除"); } } // 设置正数,表示在指定秒数后过期 protected void life999(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("life999", "life999"); cookie.setMaxAge(60 * 60); //设置Cookie一小时后被删除、无效 response.addCookie(cookie); response.getWriter().write("已经创建了一个存活一小时的Cookie"); }

6、Cookie有效路径Path的设置

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

例如:

CookieA		path=/工程路径CookieB		path=/工程路径/abc请求地址如下:	http://ip:port/工程路径/a.html		CookieA发送,CookieB不发送。	http://ip:port/工程路径/abc/a.html		CookieA发送,CookieB也发送。
//手动设置path路径    protected void testPath(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("path1", "path1"); // getContextPath() --- 获取工程路径 cookie.setPath(request.getContextPath()+"/abc"); // --- /工程路径/abc response.addCookie(cookie); response.getWriter().write("创建了一个带有Path路径的Cookie"); }

7、Cookie练习 - - - 面输入用户名登录

在这里插入图片描述

login.jsp代码如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>    Title        
用户名:
密码:

loginServlet程序代码如下:

public class loginServlet extends HttpServlet {
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username =request.getParameter("username"); String password =request.getParameter("password"); if ("wzg168".equals(username) && "123456".equals(password)){
//登陆成功 Cookie cookie = new Cookie("username", username); cookie.setMaxAge(60 * 60 * 24 * 7); // 当前的Cookie一周内有效 response.addCookie(cookie); System.out.println("登录 成功"); }else {
//登录失败 System.out.println("登录 失败"); } }}

二、Session会话

1、什么是Session会话

① Session就是一个接口(HttpSession)

② Session就是会话,它是用来维护一个客户端和服务器之间关联的一种技术。

③ 每个客户端都有自己的一个Session会话

④ Session会话中,经常用来保存用户登陆之后的信息。

2、如何创建Session和获取(id号,是否为新)

如何创建和获取Session,它们的API是一样的。

request.getSession() - - -创建/获取

第一次调用是:创建Session会话之后调用都是:获取前面创建好的Session会话对象

isNew();判断到底是不是刚创建出来的(新的)

true	表示刚创建false	表示获取之前创建

每个会话都有一个身份证号,也就是ID值,而且这个ID是唯一的。getId()得到Session的会话id值。

public class SessionServlet extends BaseServlet{
protected void createOrGetSession(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//创建和获取Session会话对象 HttpSession session = request.getSession(); //判断 当前Session会话,是否是新创建出来的 boolean isNew = session.isNew(); //获取Session会话的唯一标识id String id = session.getId(); response.getWriter().write("得到的Session,它的id是:"+ id +"
"); response.getWriter().write("这个Session是否是新创建的:"+ isNew +"
"); }}

3、Session域数据的存取

利用setAttribute、getAttribute方法

//往Session中保存数据    protected void setAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("key1","value1"); response.getWriter().write("已经往Session中保存了数据"); } //获取Session中的数据 protected void getAttribute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object attribute = request.getSession().getAttribute("key1"); response.getWriter().write("从Session中获取出key1的数据是:" + attribute); }

4、Session生命周期控制

public void setMaxInactiveInterval(int interval)	设置Session的超时时间(以秒为单位),超过指定的时长,Session就会被销毁。		值为正数的时候,设置Session的超时时长;值为负数表示永不超时(极少使用)public int getMaxInactiveInterval()					获取Session的超时时间public void invalidate()							让当前Session会话马上超时无效

Session默认的超时时长是 1800秒 - - -即半小时。

//Session中的默认超时时长    protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取的Session的默认超时时长 int maxInactiveInterval = request.getSession().getMaxInactiveInterval(); response.getWriter().write("Session的默认超时时长为:" + maxInactiveInterval + "秒"); }
因为在Tomcat服务器的配置文件web.xml中默认有以下的配置,他就表示配置了当前Tomcat服务器下所有的Session超时配置默认时长为:半小时。
30

如果说,希望当前web工程默认的Session的超时时长为其他时长,可以在次工程的web.xml配置文件中做以上相同的配置。就可以修改web工程所有Session的默认超时时长。

例如:
20

如果想要修改个别Session的超时时长,就可以使用上面的API。setMaxInactiveInterval(int interval)来进行单独的设置

session.setMaxInactiveInterval(int interval)	单独设置超时时长
//单独设置Session的超时时长 ---下面举例设置为3秒    protected void life3(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//先获取Session对象 HttpSession session = request.getSession(); //设置当前Session3秒后超时 session.setMaxInactiveInterval(3); response.getWriter().write("当前Session已经设置为3秒后超时"); }

Session超时的概念

在这里插入图片描述

设置马上超时的代码如下:利用到invalidate()方法

//设置Session马上超时(被销毁)    protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//先获取Session对象 HttpSession session = request.getSession(); //让Session会话马上超时 session.invalidate(); response.getWriter().write("Session已经设置为超时(无效)"); }

5、浏览器和Session之间关联的技术内幕

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

在这里插入图片描述

转载地址:http://mksef.baihongyu.com/

你可能感兴趣的文章
giuhub搭建及常用操作
查看>>
phpStudy安装yaf扩展
查看>>
密码 加密 加盐 常用操作记录
查看>>
TP 分页后,调用指定页。
查看>>
Oracle数据库中的(+)连接
查看>>
java-oracle中几十个实用的PL/SQL
查看>>
PLSQL常用方法汇总
查看>>
详细介绍Oracle sqlplus命令
查看>>
几个基本的 Sql Plus 命令 和 例子
查看>>
PLSQL单行函数和组函数详解
查看>>
Oracle PL/SQL语言初级教程之异常处理
查看>>
Oracle PL/SQL语言初级教程之游标
查看>>
Oracle PL/SQL语言初级教程之操作和控制语言
查看>>
Oracle PL/SQL语言初级教程之过程和函数
查看>>
Oracle PL/SQL语言初级教程之表和视图
查看>>
Oracle PL/SQL语言初级教程之完整性约束
查看>>
PL/SQL学习笔记
查看>>
如何分析SQL语句
查看>>
结构化查询语言(SQL)原理
查看>>
SQL教程之嵌套SELECT语句
查看>>