有这样一个页面p1.jsp
<body>
    <%
    for(int i=0;i<5;i++)
    {
     Cookie cookie_1 = new Cookie("aaaa"+i,i+"");
     response.addCookie(cookie_1);
    }
     %>
     <a href="p2.jsp">show cookies</a>
 </body>
还有一个页面p2.jsp
Show the cookies. <br>
    <%
     Cookie[] cookies = request.getCookies();
     for(int i=0;i<cookies.length;i++)
     {
     out.println("<h5>"+cookies[i].getName()+"="+cookies[i].getValue()+"</h5>");
     }
     %>
先打开p1.jsp
再点击超链接进入p2.jsp可以看到
Show the cookies. aaaa=4
aaaa0=0
aaaa1=1
aaaa2=2
aaaa3=3
aaaa4=4
JSESSIONID=143DDA6B3A86260D372E95B5993F85BF但是 如果我再关闭这两个窗口 再打开一个窗口 直接打开p2.jsp就会出现cookie是空 
怎么会这样 cookie不是应该保存在客户浏览器上了吗?

解决方案 »

  1.   

    你没有设置cookie的有效时间,默认是浏览器一关闭就删除cookie。
      

  2.   

    如何设置COOKIE的有效时间具体:
                Cookie cookie = new Cookie( "username", userName );
                // default cookie's age is -1, indicating the cookie will persist until browser shutdown.            // so set cookie's age to 120 days: 120 * 24 * 60 * 60 * 60 seconds
                cookie.setMaxAge( 622080000 );
                response.addCookie( cookie );
                System.out.println("Save user " + userName + " to cookie";
      

  3.   

    cookie.setMaxAge(-1); Cookie为负值,则在内存中保存,关闭浏览器就失效。为0则立即删除。cookie.setMaxAge(60); // 设置Cookie生存期为60秒...