Session和Context的比较

Session解决了Cookie记录量小,数量限制的问题,每个客户端有唯一的一个Session。
我们先往Session里放入数据
Session1

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");

        HttpSession session =request.getSession();
        session.setAttribute("name", name);

        //不同的 session有 不同的id
        response.getWriter().println(session.getId());
    }

Session2
然后我们再从Session2里取出数据,当然是同一个客户端,浏览器也会有影响。

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();
        String value = (String) session.getAttribute("name");
        out.println(value);

        out.println(session.getId());

        //request( 请求级别),ServletContext(应用), Session(会话级别)
    }

当我们访问Session1时传入的数据不同,那么我们取出的数据也不一样。每个客户端有自己唯一的Session。



下面我们再看一下context的。context的特点就是它是共用的,所有的客户端都可以取出同一条记录
context1

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

          getServletContext().setAttribute("name", "lisi");

    }

context2

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         response.setContentType("text/html;charset=utf-8");
         String value = (String) getServletContext().getAttribute("name");
         response.getWriter().println(value);

    }

只要设置过context1的值,那么所有客户端都可以访问context2取出值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值