zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Cookie 和 Session

Cookie session
2023-09-27 14:25:52 时间

在这里插入图片描述

一、会话跟踪技术

会话:用户打开浏览器,访问web服务器的资源,会话建立,直到有一方断开连接,会话结束。再一次会话中可以包含多次请求和响应
会话跟踪:一种维护浏览器状态的方法,服务器需要识别多次请求是否来自同一浏览器,以便在同一次会话的多次请求间共享数据
HTTP协议是无状态的,每次浏览器向服务器发起请求时,服务器都会将该请求视为新的请求,因此我们需要会话跟踪技术来实现会话内数据共享,实现方式:

  1. 客户端会话跟踪技术:Cookie
  2. 服务端会话跟踪技术:Session

二、Cookie

Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都带着Cookie数据进行访问
在这里插入图片描述
浏览器第一次访问服务器的时候,服务器会返回一个cookie,浏览器在次访问的时候,都会携带Cookie

Cookie基本使用

发送数据
1.创建Cookie对象,设置数据
2.发送Cookie到客户端:使用resp对象调用addCookie()

@WebServlet("/acookie")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //发送Cookie
        //1.创建Cookie对象
        Cookie cookie = new Cookie("username","zd");
        //2.发送Cookie
        resp.addCookie(cookie);
    }
}

我们在浏览器访问acookie
在这里插入图片描述
获取Cookie,接下来我们浏览器访问服务器时,就会携带Cookie
3.获取客户端携带的所有Cookie,使用req对象

Cookie[] cookies = req.getCookies();

4.遍历数组,获取每一个Cookie对象
5.使用Cookie对象的方法获取数据

cookie.getName();
cookie.getValue();

因为我们localhost有许多Cookie,所以我们需要获取所有Cookie,然后遍历选择我们需要的即可

@WebServlet("/bcookie")
public class CookieServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取Cookie
        //1.获取Cookie数组
        Cookie[] cookies = req.getCookies();
        //2.遍历数组
        for (Cookie cookie : cookies) {
            //3.获取数据
            String name = cookie.getName();
            if("username".equals(name)) {
                System.out.println(name + ": " + cookie.getValue());
                break;
            }
        }
    }
}

在这里插入图片描述
这样就实现了,一次会话中的多次请求共享数据了

Cookie原理

Cookie是基于HTTP协议实现的,响应头:set-cookie,请求头cookie
在这里插入图片描述
浏览器第一次访问服务器时,服务器响应的报头中会携带set-cookie这一字段,当浏览器后续访问时,请求的报头中就会携带Cookie字段
在这里插入图片描述
在这里插入图片描述

Cookie使用细节

Cookie存活时间: 默认情况下,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,Cookie销毁
setMaxAge(int seconds):设置Cookie存活时间:
1.正数:将Cookie写入到浏览器所在电脑的硬盘中,持久化存储,到时自动删除
2.负数:默认值,Cookie在当前浏览器内存中,当浏览器关闭,Cookie销毁
3.零:删除对应Cookie
在这里插入图片描述
在这里插入图片描述
Cookie存储中文: 我们Cookie默认是不支持存储中文的,我们演示一下
在这里插入图片描述
在这里插入图片描述
如果需要存储中文,我们需要URL转码

        String username = "张三";
        username = URLEncoder.encode(username,"utf8");
        Cookie cookie = new Cookie(username,"zd");

在这里插入图片描述

然后当服务器获取浏览器的Cookie时,在进行解码

        String value = cookie.getValue();
        value = URLDecoder.decode(value,"utf8");
        System.out.println(name + ": " + value);

Cookie四大问题:
1.Cookie是啥?
浏览器提供的持久化存储数据的机制
2.Cookie从哪里来?
Cookie是从服务器返回给浏览器的,服务器代码决定要将什么格式的信息保存到客户端,通过HTTP响应中的set-Cookie字段将键值对写回去
3.Cookie到哪去?
Cookie会在后续浏览器访问服务器时在HTTP请求header中发给服务器
4.Cookie存在哪里?
存在浏览器所在主机的硬盘上,浏览器会根据域名来分别存储

三、Session

服务端会话跟踪技术:将数据保存到服务端
JavaEE提供了HttpSession接口,来实现一次会话的多次请求间数据共享功能
在这里插入图片描述
我们A就可以往Session中写数据,B就可以从Session中读数据

Session基本使用

1.获取Seesion对象

      HttpSession session = req.getSession();

2.Session对象功能:

     void setAttribute(String name,Object o); //存储数据到seesion域中
     Object getAttribute(String name); //根据key获取值
     void removeAttribute(String name); //根据key,删除该键值对   

存储Session数据

@WebServlet("/aServlet")
public class SessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //存储Session
        //1.获取Session对象
        HttpSession session = req.getSession();
        //2.存储Session
        session.setAttribute("username","zd");

    }
}

获取Session数据

@WebServlet("/bServlet")
public class SessionServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取数据
        //1.获取Session对象
        HttpSession session = req.getSession();
        //2.获取数据
        Object username = session.getAttribute("username");
        System.out.println(username);
    }
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这样我们就通过Session实现一次通过多次请求直接实现数据共享了

Session原理

Session是基于Cookie实现的
在这里插入图片描述
因为Cookie中携带Session唯一id标识,我们第一次访问服务器时,set-Cookie中会携带一个JSESSIONID
在这里插入图片描述
我们后续请求就会携带该JSESSIONID,如果有该sessionId就直接用,否则重新创建
在这里插入图片描述

Session使用细节

Session钝化、活化:
服务器重启后,Session中的数据是否还在?
钝化:在服务器正常关闭后,Tomcat会自动将Session数据写入到硬盘文件中
活化:再次启动服务器后,从文件中加载数据到Session
Session销毁
默认情况下,无操作。30分钟自动销毁(tomcat默认配置的),我们可以在web.xml里配置
在这里插入图片描述

<session-fonfig>
    <session-timeout>30</session-timeout>
</session-fonfig>

调用Session对象的invalidate()方法

总结

Cookie和Session都是来完成一次会话内多次请求间数据共享
关联:在网站的登录功能中,需要配合使用
区别:
1.存储位置:Cookie将数据存储在客户端,Session将数据存储在服务器
2.安全性:Cookie不安全,Session安全
3.数据大小:Cookie最大3KB,Session无大小限制
4.存储时间:Cookie可以长期存储,Session默认30分钟
5.服务器性能:Cookie不占服务器资源,Session占用服务器资源
6.Cookie完全可以单独使用,不搭配Session(实现非登陆场景),Session也可以不搭配Cookie使用(手机app登录服务器,服务器也需要Session)
7.Cookie是属于HTTP协议中的一部分,Session则可以与HTTP无关(TCP,websocket等)

四、实现用户登录

我们来实现一个模拟登录,在页面中点击登录请求,验证用户名密码是否正确,如果登录成功跳转到主页,涉及到两个页面:
1.登陆页面
2.主页面
涉及到两个servlet类:
1.处理登录的LoginServlet判定用户名密码
2.构造主页面的IndexServlet
在这里插入图片描述
1.创建目录结构,编写登录页面

    <form action="login" method="post">
        <input type="text" name="username">
        <br>
        <input type="password" name="password">
        <br>
        <input type="submit" value="登录">
    </form>

在这里插入图片描述
2.编写LoginServlet处理登录请求

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //验证用户名密码是否正确,假设username = admin,password = 123
        if(!username.equals("admin") || !password.equals("123")) {
            //登录失败
            System.out.println("用户名或密码有误");
            resp.sendRedirect("login.html");
            return;
        }
        //创建会话
        HttpSession session = req.getSession(true);
        //将当前用户名保存到会话
        session.setAttribute("username",username);
        //重定向到主页
        resp.sendRedirect("index.html");
    }
}

在这里插入图片描述

该操作判断当前请求是否已经有会话了(拿着请求中Cookie里的JSESSIONID查一下哈希表),如果JSESSIONID不存在,就创建新会话并插入到哈希表中,如果查到了直接返回查到的结果,创建过程分为以下四个步骤:
1.构造一个HttpSession对象
2.构造唯一的sessionId
3.将这个键值对插入到哈希表中
4.sessionId设置到响应报文Set-Cookie中

3.编写indexServlet
在这里插入图片描述
大家需要这里的Servlet路径是和我们登录成功重定向路径一致的
在这里插入图片描述

@WebServlet("/index")
public class indexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //刚刚通过重定向发送的是GET请求
        //先判断是否登录,如果未登录,先要求登录,如果登录了将会话中的username设置到页面
        HttpSession session = req.getSession(false);
        if(session == null) {
            //未登录状态
            System.out.println("用户未登录");
            resp.sendRedirect("login.html");
            return;
        }
        String username = (String)session.getAttribute("username");
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write("欢迎 " +username+"回家");
    }
}

在这里插入图片描述
我们之所以在这里能够直接取,是因为我们在loginServlet中存过
在这里插入图片描述
根据同一个sessionId对应到同一HttpSession对象
我们来分析以下请求与相应的过程:
在这里插入图片描述
在这里插入图片描述
第一次交互:
请求:
在这里插入图片描述
第一次请求是没有Cookie的
响应:
在这里插入图片描述
我们可以发现,响应中Set-Cookie有一个SessionId,是一个唯一的数字,Location是我们要跳转到那里
第二次交互:
请求,我们浏览器重定向构造的get请求
在这里插入图片描述
我们发现是有Cookie的,Cookie中有JSESSIONID,服务器端Servlet就会在getSession方法中根据sessionId来查询HttpSession对象
响应:
在这里插入图片描述
只要完成了登录操作,后续多次请求服务器都会带上刚才Cookie中的值(sessionId)