• 【JavaWeb】Cookie&Session


    一.Cookie❤️

    1.Cookie的概念

    (1).Cookie翻译过来是饼干的意思.
    (2).Cookie是服务器通知客户端保存键值对的技术.
    (3).客户端有了Cookie后,每次请求都发送给服务器.
    (4).每个Cookie的大小不能超过4kb.

    2.创建Cookie

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
             req.setCharacterEncoding("utf-8");
             resp.setContentType("text/html;charset=utf-8");
    
            Cookie cookie = new Cookie("key1","value1");
    
            resp.addCookie(cookie);
    
            resp.getWriter().write("Cookie创建成功");
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.获取Cookie

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

    在这里插入图片描述

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
    
            Cookie[] cookies = req.getCookies();
    
            Cookie iwantCookie = CookieUtils.findCookie("key1", cookies);
    
            //       for(Cookie cookie : cookies){
            //getName()返回Cookie的key名
            // getValue()返回Cookie的Value值
            //resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "]");
    
            //if("key1".equals(cookie.getName())){
    
    //        iwantCookie = cookie;
            //  break;
            //           }
    //         }
            if (iwantCookie != null) {
                resp.getWriter().write("找到了需要的cookie");
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    public class CookieUtils {
        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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    4.修改Cookie的值

    在这里插入图片描述

    方案一:
    (1).先创建一个要修改的同名的Cookie对象
    (2).在构造器,同时赋予新的Cookie值
    (3).调用resp.addCookie(Cookie);

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
              req.setCharacterEncoding("utf-8");
              resp.setContentType("text/html;charset=utf-8");
    
              Cookie cookie = new Cookie("key1", "newvalue1");
    
                resp.addCookie(cookie);
                resp.getWriter().write("key1已经修改好了");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    方案二:
    (1).先找到需要修改的Cookie对象
    (2).调用setValue()方法赋予新的Cookie值
    (3).调用response.addCookie()通知客户端保存修改

      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              req.setCharacterEncoding("utf-8");
              resp.setContentType("text/html;charset=utf-8");
              Cookie cookie = CookieUtils.findCookie("key1", req.getCookies());
              if(cookie != null){
                cookie.setValue("newvalue2");
                resp.addCookie(cookie);//有些特殊符号例如,各种括号不支持,需要使用BASE64编码
            }
                resp.getWriter().write("key1已经修改好了");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    5.Cookie的生命周期控制

    Cookie的生命控制指的是如何管理Cookie什么时候被销毁(删除)
    setMaxAge()
    正数,表示在指定的秒数后过期
    负数,表示浏览器关闭后,cookie就会被删除
    ,表示马上删除cookie

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            Cookie cookie = new Cookie("de3","de1");
            //cookie.setMaxAge(-1);
            //cookie.setMaxAge(0);
            cookie.setMaxAge(10);
            resp.addCookie(cookie);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    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发送

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            Cookie cookie = new Cookie("path1","path1");
            //getContextPath()得到工程路径
            cookie.setPath(req.getContextPath() + "/abc");
            resp.addCookie(cookie);
            resp.getWriter().write("创建了一个带有工程路径的Cookie");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    7.免输入用户名登录

    在这里插入图片描述

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    <form action="http://localhost:8080/13_cookie_session/loginServlet" method="get">
        用户名: <input type="text" name="username" value="${cookie.username.value}"><br>
        密码: <input type="password" name="password" ><br>
        <input type="submit" value="登录">
    </form>
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            if("wzg".equals(username) && "123456".equals(password)){
                //登录成功
                Cookie cookie = new Cookie("username", username);
                cookie.setMaxAge(60*60*24*7);//当前Cookie一周内有效
                resp.addCookie(cookie);
                System.out.println("登录成功");
            }else{
                System.out.println("登录失败");
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    二.Session❤️

    1.session的概念

    (1).Session就是一个接口(HttpSession)
    (2).Session就是会话,用来维护一个客户端和服务器之间关联的一种技术
    (3).每个客户端都有自己的一个Session会话
    (4).Session会话中,我们经常用来保护用户登录之后的信息

    2.Session的创建和获取

    • 注意:创建和获取Session,使用的API是相同的.
      request.getSession():创建或者获取Session对象
      第一次调用:创建Session会话
      以后的调用:获取前面创建好的Session会话对象
    • isNew():判断是否是刚创建出来的(新的)
      true 表示刚创建
      false 表示获取之前创建
    • 注意:每个会话都有自己的一个ID,而且这个ID是唯一的
      getId() 得到Session的会话id值
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            //创建和获取Session会话对象
            HttpSession session = req.getSession();
            //判断 当前Session会话,是否是新创建出来的
            boolean isNew = session.isNew();
            //获取Session会话的唯一标识 id
            String id = session.getId();
            resp.getWriter().write("得到的Session,它的id是:" + id + "
    "
    ); resp.getWriter().write("这个Session是否是新创建的:" + isNew + "
    "
    ); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.Session域数据的存取

    • 数据的存储
      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            req.getSession().setAttribute("key1","value1");
            resp.getWriter().write("已经往Session中保存了数据");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 数据的获取
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            Object attribute = req.getSession().getAttribute("key1");
            resp.getWriter().write("从Session中获取出key1的数据是: " + attribute);
       }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4.Session的生命周期控制

    • public void setMaxInactiveInterval(int interval)
      作用:设置Session的超时时间(以秒为单位),超过指定的时长,Session就会被销毁
    • public void getMaxInactiveInterval()
      作用:获取Session的超时时间
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            //获取了Session的默认超时时长
            int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
            resp.getWriter().write("Session的默认超时时长为:" + maxInactiveInterval + "秒");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    以上代码可以了解到:Session的默认超时时间为30分钟

    • 我们可以找到你自己的web.xml文件,然后进行更改web工程所有Session的默认超时时长.
    <session-config>
            <session-timeout>20</session-timeout>
        </session-config>
    
    • 1
    • 2
    • 3
    • 如果想要改变个别Session的超时时长,就可以使用上面的API,进行单独设置
      session.setMaxInactiveInterval(int interval)

    在这里插入图片描述

     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            //先获取Session对象
            HttpSession session = req.getSession();
            //设置当前Session3秒后超时
            session.setMaxInactiveInterval(3);
            //判断 当前Session会话,是否是新创建出来的
            boolean isNew = session.isNew();
            resp.getWriter().write("当前Session已经设置为3秒后超时"+ "
    "
    ); resp.getWriter().write("这个Session是否是新创建的:" + isNew + "
    "
    ); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    注意:
    值为正数的时候,设定Session的超时时间
    值为负数的时候,表示永不超时(极少使用)

    • public void invalidate()
      作用:使当前Session会话马上超时无效
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
            //先获取Session对象
            HttpSession session = req.getSession();
            //让当前Session马上超时
            session.invalidate();
            //判断 当前Session会话,是否是新创建出来的
            boolean isNew = session.isNew();
            resp.getWriter().write("当前Session已经设置为马上超时"+ "
    "
    ); resp.getWriter().write("这个Session是否是新创建的:" + isNew + "
    "
    ); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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

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

    在这里插入图片描述

  • 相关阅读:
    【Nginx32】Nginx学习:随机索引、真实IP处理与来源处理模块
    golang 通用的 grpc http 基础开发框架
    LeetCode54螺旋矩阵、59螺旋矩阵II【灵活】
    Reggie外卖项目 —— 分类管理模块之删除分类功能
    CSS容器查询终于来了
    相机与镜头保养
    【用户画像】标签任务开发流程(源码之动态建表、常量类、配置信息、本地调试、发布运行、任务调度)
    MG动画完成练习
    多台群晖实现按计划WOL网络自动唤醒数据冷备份
    【PAT(甲级)】1072 Gas Station
  • 原文地址:https://blog.csdn.net/qq_53798578/article/details/127952524