`

为什么你的cookie删不掉

    博客分类:
  • web
阅读更多

创建cookie:

Cookie cookie1 = new Cookie("username", username);
cookie1.setMaxAge(30 * 24 * 60 * 60); //用户名保留1个月
cookie1.setPath("/");           //此时服务器上的所有页面都可以接收到该Cookie
response.addCookie(cookie1);


读取cookie:

Cookie[] cookies = request.getCookies();
    if(cookies != null){
        for(int i = 0; i < cookies.length; i++){
            if(cookies[i].getName().equals("username")){
                username=URLDecoder.decode(cookies[i].getValue(), "utf-8");
            }
        }       
    }


删除cookie:

Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(int i = 0; i < cookies.length; i++){
                Cookie temp = cookies[i];
                if(temp.getName().equals("username")){
                    if("0".equals(b1)){
                        temp.setMaxAge(0);  //设置有效时间为0,则系统会自动删除过期的cookiessss
                        temp.setPath("/");     //项目所有目录均有效,这句很关键,否则不敢保证删除
                        response.addCookie(temp);  //重新写入,将覆盖之前的
                    }
                }
            }
        }


总结: setPath设置Cookie适用的路径。如果不指定路径,Cookie将返回给当前页面(JSP页面或者Servlet的映射)所在目录及其子目录下的所有页面。

所以为什么很多时候你认为已经删除了cookie,但是在另一个页面cookie就是存在,所以一定要加上:这两段代码:

temp.setPath("/");      //项目所有目录均有效,这句很关键,否则不敢保证删除
response.addCookie(temp);   //重新写入,将覆盖之前的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics