(JavaWeb)会话跟踪技术Cookie和Session(重点)

Cookie和Session

会话

会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;

有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;

一个网站,怎么证明你来过?

客户端 服务端

  1. 服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了; cookie
  2. 服务器登记你来过了,下次你来的时候我来匹配你; seesion

保存会话的两种技术

cookie

  • 客户端技术 (响应,请求)

session

  • 服务器技术,利用这个技术,可以保存用户的会话信息? 我们可以把信息或者数据放在Session中!

常见场景:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!

Cookie

在这里插入图片描述

  1. 从请求中拿到cookie信息
  2. 服务器响应给客户端cookie

实现显示上次访问时间

public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        resp.setContentType("text/html");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //获取cookie
        Cookie[] cookies = req.getCookies();
        PrintWriter out = resp.getWriter();
        if (cookies!=null){
            out.print("你上一次访问的时间是:");
            for (int i = 0; i <cookies.length ; i++) {
                Cookie cookie = cookies[i];
                //获取cookie的键
                if (cookie.getName().equals("timing")){
                    //获取cookie的值
                    long lasteLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lasteLoginTime);
                    out.print(date.toLocaleString());
                }
            }
        }else {
            out.print("这是你第一次访问");
        }
        //创建一个cookie存放上次访问的时间
        Cookie cookie = new Cookie("timing",System.currentTimeMillis()+"");
        //设置cookie存活时间为1天
        cookie.setMaxAge(24*60*60);
        //添加cookie
        resp.addCookie(cookie);
    }

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

第一次访问
在这里插入图片描述
第二次访问
在这里插入图片描述
有的浏览器第一次就会有一些cookie,这里用的是Microsoft edge。

Session

在这里插入图片描述
什么是Session:

  • 服务器会给每一个用户(浏览器)创建一个Seesion对象;
  • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
  • 用户登录之后,整个网站它都可以访问!

在这里插入图片描述

Session和cookie的区别:

  • Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
  • Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
  • Session对象由服务创建;

使用场景:

  • 保存一个登录用户的信息;
  • 购物车信息;
  • 在整个网站中经常会使用的数据,我们将它保存在Session中;

Session的使用

得到session并向其中存放person对象,输出sessionID信息

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //得到Session
        HttpSession session = req.getSession();
        //向session中存东西
        session.setAttribute("person",new Person("伊泽瑞尔",18));
        //存放session id
        String id = session.getId();
        if (session!=null){
            resp.getWriter().write("session创建成功,id为:"+id);
        }else {
            resp.getWriter().write("session已经存在,id为:"+id);
        }
    }

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

后台输出session对象信息

public class SessionDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //得到Session
        HttpSession session = req.getSession();
        Person person = (Person) session.getAttribute("person");
        System.out.println(person.toString());
    }

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

手动注销session

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //得到Session
        HttpSession session = req.getSession();
        session.removeAttribute("person");
        //手动注销session
        session.invalidate();
    }

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

设置session失效时间

  <session-config>
    <!--设置session失效时间为1分钟-->
    <session-timeout>1</session-timeout>
  </session-config>

第一次访问页面创建了一个sessionID
在这里插入图片描述
访问SessionDemo02后台输出session保存的person对象信息
在这里插入图片描述
在这里插入图片描述
访问SessionDemo03注销session
在这里插入图片描述
再次访问SessionDemo01又新创建了一个session,id和第一次访问的不同。
在这里插入图片描述

session实现购物车功能

jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>请选择你要购买的书籍</h1>
<form action="${pageContext.request.contextPath}/ShoppingCarDemo01" method="get">
    <input type="checkbox" name="book" value="JavaSE"/>JavaSE <br/>
    <input type="checkbox" name="book" value="JavaWeb"/>JavaWeb <br/>
    <input type="checkbox" name="book" value="JavaEE"/>JavaEE <br/>
    <input type="submit" value="提交">
</form>
</body>
</html>

处理书籍信息的servlet

public class ShoppingCarDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //获取session对象
        HttpSession session = req.getSession();
        Map<String,Integer> car = (Map<String, Integer>) session.getAttribute("shoppingCar");
        if(car==null){
            car = new HashMap<>();
        }
        //获取客户端数据
        String[] books = req.getParameterValues("book");
        if (books!=null && books.length>0){
            for (String book : books) {
                if (car.get(book)!=null){
                    int num = car.get(book);
                    car.put(book,num+1);
                }else {
                    car.put(book,1);
                }
            }
        }
        session.setAttribute("shoppingCar",car);
        //重定向到购物车页面
        resp.sendRedirect("/demo02_war/ShoppingCarDemo02");
    }

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

显示购物车信息的servlet

public class ShoppingCarDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码问题
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //获取session对象
        HttpSession session = req.getSession();
        Map<String,Integer> car = (Map<String, Integer>) session.getAttribute("shoppingCar");
        if (car != null &&car.size()>0){
            out.print("您购买的书籍有");
            for (String bookName : car.keySet()) {
                out.print("<p>"+bookName+":"+car.get(bookName)+"本<p>");
            }
        }else {
            out.print("您还未购买任何书籍");
        }

        out.print("<p><a href='bookChoose.jsp'>继续购买</a></p>");
    }

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

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值