加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 删除servlet中的cookie的问题

发布时间:2020-12-15 00:48:16 所属栏目:Java 来源:网络整理
导读:我尝试使用此代码删除servlet中的cookie Cookie minIdCookie = null;for (Cookie c : req.getCookies()) { if (c.getName().equals("iPlanetDirectoryPro")) { minIdCookie = c; break; }}if (minIdCookie != null) { minIdCookie.setMaxAge(0); minIdCookie
我尝试使用此代码删除servlet中的cookie
Cookie minIdCookie = null;

for (Cookie c : req.getCookies()) {
    if (c.getName().equals("iPlanetDirectoryPro")) {
        minIdCookie = c;
        break;
    }
}

if (minIdCookie != null) {
    minIdCookie.setMaxAge(0);
    minIdCookie.setValue("");
    minIdCookie.setPath("/");
    res.addCookie(minIdCookie);
}

res.flushBuffer();

但是这没有效果,也没有改变cookie属性.

我也尝试在这个servlet中添加一个cookie,这很好用.

为什么我无法更改现有cookie的属性.

解决方法

你不应该改变路径.这会改变cookie身份.如果为/ foo这样的路径设置了cookie并将其更改为/,则客户端将不再将更改的cookie与原始cookie相关联. Cookie由名称和路径标识.

将maxage设置为0应该足够了.

Cookie[] cookies = request.getCookies();
if (cookies != null) { // Yes,this can return null! The for loop would otherwise throw NPE.
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals("iPlanetDirectoryPro")) {
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            break;
        }
    }
}

您还需要确保在后续新请求中读取/测试cookie,而不是在当前请求中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读