Cookie和Session

1.Cookie入门

(1)代码展示

(2)分析1

 

(3)分析2

 

(4)分析4

5).关闭浏览器,如果没有写入有效时长的Cookie就会失效,Cookie的生命周期也算是结束

 

2.JSP介绍

 (1)定义,执行流程,语法

 

3.获取上次登录时间的Demo

 (1)利用Cookie技术

 

(2).效果图(没有持久化Cookie的情况)

 

 (3).效果图(持久化Cookie的情况)

 

 4.客户端会话技术之Cookie

 (1)概叙

 

(2)Cookie

 

(3)Cookie踩过的坑

 

(4)还有两个注意的地方

 

5.服务器会话技术之session

 (1)概叙

 

6.利用session存放私有数据(案例把购物车当成个session)

 (1)分析步骤

 

(2)加入购物车servlet,点击加入购物车时(/day1101/add2Cart?name=衣服)

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0.设置编码
        response.setContentType("text/html;charset=utf-8");
        PrintWriter w = response.getWriter();
        
        //1.获取商品的名称
        String name=request.getParameter("name");
        name=new String(name.getBytes("iso8859-1"),"utf-8");
        
        //2.将商品添加到购物车
        //2.1 从session中获取购物车
        Map<String,Integer> map=(Map<String, Integer>) request.getSession().getAttribute("cart");
        
        Integer count=null;
        
        //2.2判断购物车是否为空
        if(map==null){
            //第一次购物  创建购物车 
            map=new HashMap<>();
            
            //将购物车放入session中g
            request.getSession().setAttribute("cart", map);
            
            count=1;
        }else{
            //购物车不为空 继续判断购物车中是否有该商品
            count = map.get(name);
            if(count==null){
                //购物车中没有该商品
                count=1;
            }else{
                //购物车中有该商品
                count++;
            }
        }
        //将商品放入购物车中
        map.put(name, count);
        
        //3.提示信息
        w.print("已经将<b>"+name+"</b>添加到购物车中<hr>");
        w.print("<a href='"+request.getContextPath()+"/product_list.jsp'>继续购物</a>&nbsp;&nbsp;&nbsp;&nbsp;");
        w.print("<a href='"+request.getContextPath()+"/cart.jsp'>查看购物车</a>&nbsp;&nbsp;&nbsp;&nbsp;");
    }

(3).利用jsp动态展示

 

(4)清空购物车

 

posted @ 2018-07-12 14:17  Jeffery336699  阅读(214)  评论(0编辑  收藏  举报