问答详情
源自:8-8 使用Cookie实现保存商品浏览记录

哪位大神逐行解释一下?有点稀里糊涂的!感谢!!

String list ="";
        
              Cookie[] cookies = request.getCookies();
            
              if(cookies!=null&&cookies.length>0)
              {
	              for(Cookie c:cookies)
	              {
	                  if(c.getName().equals("ListViewCookie"))
	                  {
	                     list = c.getValue();
	                  }
	              }
	          }
              
              list+=request.getParameter("id")+",";
              //如果浏览记录超过1000条,清零.
              String[] arr = list.split(",");
              if(arr!=null&&arr.length>0)
              {
                  if(arr.length>=1000)
                  {
                      list="";
                  }
              }
              Cookie cookie = new Cookie("ListViewCookie",list);
              response.addCookie(cookie);

cookie这一章确实还需再看几遍

提问者:Juneava 2016-11-17 20:09

个回答

  • Airly
    2016-11-23 01:13:50
    已采纳

    cookie本身是有生命周期的,即有个过期时间。

    下面这段代码的用途是来判断是否有匹配的cookie,如果有,执行这行代码   list = c.getValue();

     Cookie[] cookies = request.getCookies();

                  //遍历这个Cookies集合

                  if(cookies!=null&&cookies.length>0)

                  {

                      for(Cookie c:cookies)

                      {

                          if(c.getName().equals("ListViewCookie"))

                          {

                             list = c.getValue();

                          }

                      }

                  }

    如果没有,则上面这段代码将不被执行,直接执行下面这段代码


     list+=request.getParameter("id")+",";

                  //如果浏览记录超过1000条,清零.

                  String[] arr = list.split(",");

                  if(arr!=null&&arr.length>0)

                  {

                      if(arr.length>=1000)

                      {

                          list="";

                      }

                  }

                  Cookie cookie = new Cookie("ListViewCookie",list);

                  response.addCookie(cookie);


    实际上项目第一次被执行的时候是先执行的第2段代码,然后第二次才是执行的第1段代码

    ---------------------------------------------------------------------------------------------------

    至于cookie里面存的值:

    举个例子,当我点击的id为1的商品, 则list=“1,”;

                            点击id为2的商品,则list ="1,2,";

    因为 list+=request.getParameter("id")+","; 等同于 list = list + request.getParameter("id")+","

    即重新覆盖原来字符串的意思。


  • qq_四非_0
    2016-11-17 20:40:18

    新建cookie,然后往cookie里面放东西,之后取出来遍历,判断有没有超过一千