删除cookie

时间:2012-07-06 10:02:38

标签: servlets

如何使用servlet从客户端浏览器中删除cookie?

      HttpSession ses=request.getSession(false);
        Cookie c[]=request.getCookies();

        for (int i=0; i<c.length; i++)  //Removing cookie, if present
        {
            if(c[i].getName().equals("UserID"))
            {
                System.out.println(c[i].getValue()+" is logging out --- Cookie Set to expire!");
                c[i].setMaxAge(0);
                response.addCookie(c[i]);
                break;
            }
        }

有没有其他方法可以删除它????

1 个答案:

答案 0 :(得分:1)

setMaxAge(0)是删除Cookie的唯一方法。最好在删除时设置这些cookie属性:

  • 路径
  • Cookie c[]=request.getCookies();
    
    for (int i=0; i<c.length; i++)  //Removing cookie, if present
    {
        if(c[i].getName().equals("UserID"))
        {
            System.out.println(c[i].getValue()+" is logging out --- Cookie Set to expire!");
            c[i].setMaxAge(0);
            c[i].setPath(path);
            c[i].setDomain(domain);
            response.addCookie(c[i]);
            break;
        }
    }