IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Cookie和Session的初步理解 -> 正文阅读

[网络协议]Cookie和Session的初步理解

一:Cookie

1.1 信件/凭证:

??????当用户通过浏览器访问web网页,即请求web资源时,用来证明当前浏览器访问过目标网站的信件,对应响应信件内容或其他资源。

1.2 实现:

可以对要访问的页面的添加Cookie,返回到浏览器保存:
resp.addCookie(new Cookie(name,vale))

1.3 请求过程

当浏览器访问时会携带Cookie,如果携带的Cookie符合则对应设置的的值取出对应响应内容:
??????1.获取Cookie: req.getCookie()
??????2.获取Cookie的key: cookie.getName()
??????3.获取Cookie的value:cookie.getValue()

1.4 设置有效期

设置器浏览器保存的Cookie有效期时间:
setMaxAge(time);单位s

1.5 删除cookie

1.不设置Cookie的有效期,浏览器关闭后自动销毁了
2.设置Cookie的有效期到期自动删除(失效)

1.6 解决乱码

1.resp:设置响应格式(例"text/html")和设置响应编码(例"utf-8")
???????resp.setCharacterEncoding(“utf-8”)
???????resp.setContentType(“text/html”)

2.req:设置请求编码(例"utf-8")和建立保存至浏览器时编码UrlEncoder与获取请求时解码UrlDecoder

1.7 源码

package com.zk.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;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Cookie:
 *      1.信件/凭证:当浏览器访问web网页,即请求web资源,用来证明当前浏览器访问过的信件,对应响应信件
 *      2.实现:可对要访问的页面的resp.addCookie(new Cookie(name,vale)),返回到浏览器保存
 *      3.请求过程:当浏览器访问时会携带req.getCookie(),如果携带的cookie.getName()符合则cookie.getValue取出对应响应
 *      4.设置有效期:setMaxAge(time);单位s
 *      5.删除cookie:
 *              a.不设置cookie的有效期,浏览器关闭后自动没有
 *              b.设置cookie.setMaxAge(),到期自动删除(失效)
 *      6.解决乱码:
 *              a.resp:设置响应格式(例"text/html")和设置响应编码(例"utf-8")
 *              b.req:设置请求编码(例"utf-8")和建立保存至浏览器时编码UrlEncoder与获取请求时解码UrlDecoder
 *
 * 
 */
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.从网站的请求获取Cookie;可能有多个,数组接收
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        Cookie[] cookies = req.getCookies();
        PrintWriter writer = resp.getWriter();
        if (cookies==null){
            writer.print("第一次访问");
        }else {
            boolean judge=false;
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                //2.获取cookie的name看看是不是当前服务器设置的
                if (cookie.getName().equals("time")){
                    judge=true;
                    //3.如果是则获取其值
                    writer.print("上次访问时间为:" + (new Date(Long.parseLong(cookie.getValue()))).toLocaleString());
                    System.out.println("上次访问时间"+(new Date(Long.parseLong(cookie.getValue()))).toLocaleString());
                }
            }
            if (!judge){
                writer.print("第一次访问");
            }
        }
        //4.创建cookie
        Cookie cookie = new Cookie("time", System.currentTimeMillis() + "");
        //5.设置cookie的有效期:单位秒
        cookie.setMaxAge(24*60*60);
        //6.给网站响应一个新的当前时间
        System.out.println("当前访问时间"+(new Date(Long.parseLong(cookie.getValue()))).toLocaleString());
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

1.8 结果

1.第一次访问:在这里插入图片描述
2.浏览浏览器的Cookie:
在这里插入图片描述
3.控制台输出
在这里插入图片描述

二:Session

2.1 Session理解

??????1.Session是与客户端(浏览器)绑定的,在不同的客户端中其不同,客户端退出就删除了,重启又会重新生成
??????2.Session在客户端打开网页就有了,封装在Cookie中的
??????3.其Session中的属性可以是自定义类,设置的属性也只与当前的浏览器关联,其他浏览器访问是没有

2.2 注销Session

1.退出浏览器:退出浏览器后Session就销毁了
2.调用session.invalidate()手动注销
3.在web.xml配置session-config中的timeout,其单位为分

<session-config>
    <session-timeout>1</session-timeout>
  </session-config>

2.3 Session测试

自定义类

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "{姓名为:"+this.name+" 年龄为:"+this.age+"}";
    }
}

测试类

package com.zk.session;

import com.zk.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 要点:
 *      1.Session是与客户端(浏览器)绑定的,在不同的客户端中其不同,客户端退出就删除了,重启又会重新生成
 *      2.Session在客户端打开网页就有了,封装在Cookie中的
 *      3.其Session中的属性可以是自定义类,设置的属性也只与当前的浏览器关联,其他浏览器访问是没有
 *      4.注销Session
 *              1.退出浏览器
 *              2.调用session.invalidate()
 *              3.在web.xml配置session-config中的timeout单位分
 *              4.注意:在没有退出浏览器注销后其session依旧会重新生成
 *
 *
 */
public class SessionServlet 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");
        //获取Session
        HttpSession session = req.getSession();
        //设置Session属性
        session.setAttribute("id",new Person("张三",22));
        //获取Session的id
        String sessionId = session.getId();
        //判断Session是否新创建的
        if (session.isNew()){
            resp.getWriter().write("Session创建成功:"+sessionId);
        }else {
            resp.getWriter().write("Session已经创建了:"+sessionId);
        }
        //测试Session的来源
        resp.getWriter().write("<br>");
        Cookie[] cookies = req.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("JSESSIONID")){
                resp.getWriter().write("Cookie封装的Session信息:"+cookies[i].getValue());
            }
        }
        //获取输出设置的属性
        resp.getWriter().write("<br>");
        resp.getWriter().write("Session属性值为:"+session.getAttribute("id").toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.4 获取Session的属性

package com.zk.session;

import com.zk.pojo.Person;

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 SessionGetAttribute extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        HttpSession session = req.getSession();
        Person person = (Person) session.getAttribute("id");
        resp.getWriter().write("属性值为:"+person.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.5 手动注销Session

package com.zk.session;

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 SessionInvalidate extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.6 运行结果

1.打开谷歌浏览器
在这里插入图片描述
?
?
?
2.打开360浏览器
在这里插入图片描述

不同的浏览器访问其Session的ID不同

?
?
?
3.在谷歌浏览器中访问SessionServlet后不关闭浏览器新建标签页访问SessionServlet
在这里插入图片描述
在这里插入图片描述

在访问后不关闭浏览器继续重新访问和关闭当前页新建标签页访问其Session都不变

?
?
?
4.访问SessionServlet添加属性
在这里插入图片描述

?
?
?
5.访问SessionGetAttribute获取属性
在这里插入图片描述
?
?
?
6.访问SessionInvalidate手动注销后不关闭浏览器重新访问
在这里插入图片描述

其Session也变了

?
?
?
7.在谷歌浏览器中访问SessionServlet添加属性后在360浏览器访问SessionGetAttribute获取属性
在这里插入图片描述

在360浏览器中报错,Session只与当前浏览器绑定

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-11-18 11:30:16  更:2021-11-18 11:30:41 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年7日历 -2024/7/3 22:13:05-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码