Day_08 会话技术 Cookie和Cookie

01-会话技术介绍(掌握)

  • 为什么?
    • ServeltRequest域对象的共享范围太小了;
    • ServletContext域对象的共享范围太大了。
  • 概述
    • 当打开浏览器,访问网站地址后,会话开始,当关闭浏览器(或 者到了过期时间),会话结束。
  • 分类
    • Cookie : 浏览器端的会话技术
      • 数据保存在浏览器
    • Session : 服务器端的会话技术
      • 数据保存在服务器
  • 作用
    • 在一次会话中,存储数据并实现共享。

02-Cookie概述(掌握)

  • 概述

    Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. 
    
    A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets. 
    
    The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each. 
    
    The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method. Several cookies might have the same name but different path attributes. 
    
    • Cookie对象,用于携带少量数据通过Servlet发送给浏览器,并且保存在浏览器,随后发送回服务器,所以往往用于会话管理;
    • Cookie对象,有必须属性name和value,还有一些可选属性path、a maximum age,不同的浏览器对可选属性的支持不太一样;
    • 服务器发送Cookie给浏览器,是通过HttpServletResponse.addCookie操作响应头Set-Cookie来完成;
    • 浏览器,同一时间,每个项目最多20个Cookie,总共300个Cookie,每个Cookie中的数据最多4KB;
    • 浏览器发送Cookie给服务器,服务器是通过 HttpServletRequest.getCookies操作请求头Cookie来获取。
  • 常用属性

    • name、value、path、a maximum age

03-Cookie基本使用(掌握)

  • 代码实现

    /**
     * 03-Cookie基本使用
     * ①创建Cookie,并将其发送给浏览器保存
     */
    @WebServlet("/demo01")
    public class Demo01Servlet  extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            Cookie cookie = new Cookie("msg","hello");
            //操作响应头Set-Cookie
            resp.addCookie(cookie);
    
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    /**
     * 03-Cookie基本使用
     * ②获取浏览器发送过来的cookie
     */
    @WebServlet("/demo02")
    public class Demo02Servlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //获取浏览器发送过来的Cookie,通过请求头Cookie来获取
            Cookie[] cookies = req.getCookies();
            Cookie myCookie = null;
            if (null == cookies || 0 == cookies.length) {
    
            } else {
                for (Cookie cookie : cookies) {
                    if ("msg".equals(cookie.getName())) {
                        myCookie = cookie;
                    }
                }
            }
    
            if (null == myCookie) {
                System.out.println("没有找到cookie");
            } else {
                System.out.println("name = " + myCookie.getName() + " , value = " + myCookie.getValue());
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    

04-Cookie执行流程(掌握)

  • 执行流程
    • image-20220314140757862

05-Cookie相关设置(掌握)

  • ①值限制

    • Cookie 的值不能包含逗号、分号、空格,不能以$开头。
  • ②存活时长限制

    • -1 : 默认值,会话结束,Cookie就销毁
    • 正数:Cookie存活时长,以秒为单位
    • 0 : 立即销毁Cookie
  • ③访问路径限制

    • 默认值:"/项目访问路径";设置什么时候需要携带Cookie
  • ①值限制

    @WebServlet("/demo03")
    public class Demo03Servlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            Cookie cookie = new Cookie("msg2","hello,2");//错误示范
            resp.addCookie(cookie);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • ②存活时长限制

    /**
     * 05-Cookie相关设置
     * ②存活时长限制
     */
    @WebServlet("/demo04")
    public class Demo04Servlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            Cookie cookie = new Cookie("msg3", "hello3");
            cookie.setMaxAge(7 * 24 * 60 * 60);
            resp.addCookie(cookie);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  • ③访问路径限制

    /**
     * 05-Cookie相关设置
     * ③访问路径限制
     */
    @WebServlet("/demo05")
    public class Demo05Servlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            Cookie cookie = new Cookie("msg4", "hello4");
            cookie.setPath(req.getContextPath() + "/demo02");
            resp.addCookie(cookie);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    

06-Cookie的销毁(掌握)

  • 开发步骤

    • ①创建Cookie对象
      • 指定name属性
    • ②设置path属性
    • ③设置maxAge=0
    • ④将Cookie响应给浏览器
  • 代码实现

    /**
     * 06-Cookie的销毁
     */
    @WebServlet("/demo06")
    public class Demo06Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //①创建Cookie对象
            Cookie cookie = new Cookie("msg4", "aaa");
            //②设置path属性
            cookie.setPath("/day08/myDemo02");
            //③设置maxAge=0
            cookie.setMaxAge(0);
            //④将Cookie响应给浏览器
            response.addCookie(cookie);
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    

07-Cookie练习(掌握)

  • 需求

    • 显示商品浏览记录
  • 开发步骤

    • ①定义shopping.html
      • 显示商品列表
    • ②添加历史记录
    • ③获取历史记录
    • ④展示历史记录
  • ①定义shopping.html

    /**
     * 转发到shopping-list.html
     *
     * @param request
     * @param response
     */
    public void toShoppingListPage(HttpServletRequest request, HttpServletResponse response) {
        try {
            processTemplate("shopping-list", request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>商品列表</title>
    </head>
    <body>
    
    <a th:href="@{/shopping(method=addHistory,id=0)}">西游记</a><br>
    <a th:href="@{/shopping(method=addHistory,id=1)}">红楼梦</a><br>
    <a th:href="@{/shopping(method=addHistory,id=2)}">三国演义</a><br>
    <a th:href="@{/shopping(method=addHistory,id=3)}">水浒传</a><br>
    
    <a th:href="@{/shopping(method=showHistory)}">查看历史记录</a>
    
    
    </body>
    </html>
    
  • ②添加历史记录

    /**
     * 添加历史记录
     * @param request
     * @param response
     */
    public void addHistory(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        System.out.println("ShoppingServlet addHistory " + id);
    
        Cookie[] cookies = request.getCookies();
        Cookie myCookie = null;
        if (null == cookies || 0 == cookies.length) {
        } else {
            for (Cookie cookie : cookies) {
                if ("history".equals(cookie.getName())) {
                    myCookie = cookie;
                }
            }
        }
        if (null == myCookie) {
            //第一次浏览
            myCookie = new Cookie("history",id);
        } else {
            //不是第一次浏览器 , 商品之前是否浏览过?
            //0-1
            String historyStr = myCookie.getValue();
            if (!historyStr.contains(id)) {
                historyStr = historyStr + "-" + id;
            }
            myCookie.setValue(historyStr);
        }
    
        response.addCookie(myCookie);
    
    
    }
    
  • ③获取历史记录

    /**
     * 展示历史浏览记录
     *
     * @param request
     * @param response
     */
    public void showHistory(HttpServletRequest request, HttpServletResponse response) {
        //获取历史浏览记录
        String[] shoppingNames = {"西游记", "红楼梦", "三国演义", "水浒传"};
        Cookie[] cookies = request.getCookies();
        Cookie myCookie = null;
        if (null == cookies || 0 == cookies.length) {
        } else {
            for (Cookie cookie : cookies) {
                if ("history".equals(cookie.getName())) {
                    myCookie = cookie;
                }
            }
        }
        List<String> shoppingNameList = new ArrayList<>();
        if (null == myCookie) {
            //没有历史记录
        } else {
            //有历史记录 : 0-1-2-3
            String historyStr = myCookie.getValue();
            String[] historyIndexStrs = historyStr.split("-");
            for (String historyIndexStr : historyIndexStrs) {
                Integer historyIndex = Integer.parseInt(historyIndexStr);
                String shoppingName = shoppingNames[historyIndex];
                shoppingNameList.add(shoppingName);
            }
        }
    
        request.setAttribute("shoppingNameList", shoppingNameList);
        try {
            processTemplate("shopping-history", request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    
  • ④展示历史记录

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>历史列表</title>
    </head>
    <body>
    
    
    <span th:if="${shoppingNameList==null||#lists.size(shoppingNameList)==0}">
        您还没有浏览过任何商品,<a th:href="@{/shopping(method=toShoppingListPage)}">去看看!</a>
    </span>
    
    <span th:unless="${shoppingNameList==null||#lists.size(shoppingNameList)==0}">
        商品浏览记录如下:<br>
        <ul>
            <li th:each="shoppingName:${shoppingNameList}" th:text="${shoppingName}"></li>
        </ul>
    
    </span>
    
    
    </body>
    </html>
    

08-Session介绍(掌握)

  • 概述

    Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. 
    
    • Session对象,提供了一种方式可以在多个web页面之间实现存储数据并共享。
    • 只不过在客户端保存的是一个特殊标识,而共享的数据保存到了服务器端的内存对象中。每次请求 时,浏览器都会将特殊标识携带到服务器端,根据这个标识来找到对应的内存空间,从而实现共享。
  • 三大域对象

    • ServletRequest、HttpSesion、ServletContext

09-Session基本使用(掌握)

  • 代码实现

    @WebServlet("/demo07")
    public class Demo07Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession session = request.getSession();
            System.out.println("Demo07Servlet session = " + session.getId());
            session.setAttribute("msg","hello");
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
    @WebServlet("/demo08")
    public class Demo08Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession session = request.getSession();
            System.out.println("Demo08Servlet session = " + session.getId());
            Object msg = session.getAttribute("msg");
            System.out.println("msg = " + msg);
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
    @WebServlet("/demo09")
    public class Demo09Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession session = request.getSession();
            System.out.println("Demo09Servlet session = " + session.getId());
            session.removeAttribute("msg");
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    

10-Session执行流程(掌握)

  • 执行流程
    • image-20220314162310520

11-Cookie相关配置(掌握)

  • ①生命周期

    • 默认情况下,Session对象存活时长为30分钟;
    • 可以通过在web.xml中,设置来对session存活时长进行配置;
    • 也可以通过session.setMaxInactiveInterval()进行配置
  • ②session销毁

    • 通过session.invalidate()方法进行销毁
  • ①生命周期

    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>
    
    @WebServlet("/demo10")
    public class Demo10Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(10);
            System.out.println("Demo10Servlet session = " + session.getId());
            session.setAttribute("msg","hello");
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
  • ②session销毁

    @WebServlet("/demo14")
    public class Demo14Servlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession session = request.getSession();
            System.out.println("Demo14Servlet session = " + session.getId());
            session.invalidate();
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    }
    
  • 注意事项

    • 当用户关闭浏览器,并没有销毁服务器中的Sesion对象,它会遵守web.xml中30分钟的默认存活时长;
    • 但是,浏览器中的Cookie销毁了,意味着JSESSIONID没有了,意味着后续的请求,服务器认为是一个新的会话,所以会创建新的Session对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值