删除servlet中的cookie的问题 [英] Problem removing cookie in servlet

查看:351
本文介绍了删除servlet中的cookie的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此代码删除servlet中的Cookie

I trying to remove a cookie in a servlet with this code

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属性没有变化。

But this gives no effect and no change in the cookie properties.

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

I've also tried adding a cookie in this servlet and this works fine.

为什么我不能改变现在的cookie。

Why is it that I can not change the properties of an existing cookie.

推荐答案

问题是我要删除的cookie有一个路径是/ admin servlet具有路径/ admin / logoutServlet。当我从请求获取cookie的路径设置为null。所以当我添加cookie的路径设置为/ admin /作为我的servlet如果我创建一个cookie,路径/ admin /servlet能够删除它。

The problem was that the cookie I wanted to remove had a path that was "/admin" and my logout servlet had the path "/admin/logoutServlet". When I get the cookie from the request the path is set to null. So when I add the cookie the path is set to "/admin/" as my servletIf I created a cookie with the path "/admin/" the servlet was able to remove it.

我通过在将cookie添加到响应之前明确设置cookie的路径来解决了这个问题。

I solved the problem by explisitly setting the path of the cookie before adding it to the response.

minIdCookie.setMaxAge(0);
minIdCookie.setPath("/");
res.addCookie(minIdCookie);

但我不明白为什么路径为空。

But I don't understand why the path is null.

这篇关于删除servlet中的cookie的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆