java 在 servlet 中删除 cookie 的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3466267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:57:52  来源:igfitidea点击:

Problem removing cookie in servlet

javahttpservletscookies

提问by Stefan Rasmusson

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

我尝试使用此代码删除 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();

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

但这不会影响 cookie 属性,也不会改变。

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

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

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

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

采纳答案by Stefan Rasmusson

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 的路径是“/admin”,而我的注销 servlet 的路径是“/admin/logoutServlet”。当我从请求中获取 cookie 时,路径设置为 null。因此,当我添加 cookie 时,路径设置为“/admin/”作为我的 servlet 如果我使用路径“/admin/”创建了一个 cookie,servlet 能够将其删除。

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

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

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

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

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

回答by BalusC

You should not change the path. This would change the cookie identity. If the cookie were set for a path like /fooand you change this to /, then the client won't associate the changed cookie with the original cookie anymore. A cookie is identified by the name and the path.

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

Just setting maxage to 0 ought to be enough.

只需将 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;
        }
    }
}

You also need to ensure that you're reading/testing the cookie in the subsequent newrequest, not in the current request.

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

回答by Stefan Rasmusson

I understand this is a few years old now, but the answer BalusC gave above isn't entirely correct, nor does Stefan's accepted answer really give all the details.

我知道这已经有几年了,但是 BalusC 上面给出的答案并不完全正确,Stefan 接受的答案也没有真正提供所有细节。

The path and domain will always be null when you retrieve cookies in Java because they are only necessary in the response for the client browser. However, if you're in the same security domain (regardless of the path), you still have the rights to delete them. Unfortunately, because the path is not included you can't delete the cookie now without explicitly knowing that path. Simply using the same cookie name, but a different path will not work. Those are considered two different cookies, and you will find that instead of deleting the cookie, you just created another one on a different path.

当您在 Java 中检索 cookie 时,路径和域将始终为空,因为它们仅在客户端浏览器的响应中是必需的。但是,如果您在同一个安全域中(无论路径如何),您仍然有权删除它们。不幸的是,由于未包含该路径,您现在无法在不明确知道该路径的情况下删除 cookie。简单地使用相同的 cookie 名称,但不同的路径是行不通的。它们被视为两种不同的 cookie,您会发现您没有删除 cookie,而是在不同的路径上创建了另一个 cookie。

The other problem most developers have is they try to check for the absence of cookies before the response has been committed. A cookie is not removed until the client browser can read the response and remove it from the file system. If you forward to another servlet with the hope that you have deleted a cookie you will find it still exists (since the initial request is the same). In this sense request attributes are a much better option.

大多数开发人员面临的另一个问题是,他们会在提交响应之前尝试检查是否缺少 cookie。在客户端浏览器可以读取响应并将其从文件系统中删除之前,cookie 不会被删除。如果您转发到另一个 servlet 并希望您删除了一个 cookie,您会发现它仍然存在(因为初始请求是相同的)。从这个意义上说,请求属性是一个更好的选择。

回答by ath j

Most of the time the problem is with path of the cookie. So take care that you specify the path when creating a cookie. And then use the same path while discarding a cookie. The concept of path is

大多数情况下,问题出在 cookie 的路径上。因此,在创建 cookie 时请注意指定路径。然后在丢弃cookie的同时使用相同的路径。路径的概念是

public String getPath() public void setPath(String path) These methods get or set the path to which the cookie applies. If you don't specify a path, the browser returns the cookie only to URLs in or below the directory containing the page that sent the cookie. For example, if the server sent the cookie from //ecommerce.site.com/toys/specials.html, the browser would send the cookie back when connecting to //ecommerce.site.com/toys/bikes/beginners.html, but not to //ecommerce.site.com/cds/classical.html. The setPath method can be used to specify something more general. For example, someCookie.setPath("/") specifies that all pages on the server should receive the cookie. The path specified must include the current page; that is, you may specify a more general path than the default, but not a more specific one. So, for example, a servlet at //host/store/cust-service/request could specify a path of /store/ (since /store/ includes /store/cust-service/) but not a path of /store/cust-service/returns/ (since this directory does not include /store/cust-service/).

public String getPath() public void setPath(String path) 这些方法获取或设置cookie 应用的路径。如果您不指定路径,则浏览器仅将 cookie 返回到包含发送 cookie 的页面的目录中或下方的 URL。例如,如果服务器从 //ecommerce.site.com/toys/specials.html 发送 cookie,则浏览器会在连接到 //ecommerce.site.com/toys/bikes/beginners.html 时将 cookie 发送回来,但不是//ecommerce.site.com/cds/classical.html。setPath 方法可用于指定更通用的内容。例如, someCookie.setPath("/") 指定服务器上的所有页面都应该接收 cookie。指定的路径必须包含当前页面;也就是说,您可以指定比默认路径更通用的路径,但不能指定更具体的路径。

to get more info of path and cookie relate properties you can visit here.

要获取有关路径和 cookie 相关属性的更多信息,您可以访问此处

回答by ath j

I think it is better to be using nullinstead of empty string. ie. change minIdCookie.setValue("");to minIdCookie.setValue(null);

我认为最好使用null而不是空字符串。IE。更改 minIdCookie.setValue("");minIdCookie.setValue(null);