简体   繁体   English

如何删除 Java Servlet 中的 Cookie

[英]How do you remove a Cookie in a Java Servlet

How do you remove a cookie in a Java servlet?如何删除 Java servlet 中的 cookie?

I tried this: http://www.jguru.com/faq/view.jsp?EID=42225我试过这个: http ://www.jguru.com/faq/view.jsp?EID=42225

EDIT: The following now works successfully it appears to be the combination of:编辑:以下现在可以成功运行,它似乎是以下组合:

response.setContentType("text/html");

and

cookie.setMaxAge(0);

Before I was doing:在我做之前:

//remove single signon cookie if it hasn't been validated yet
response.setContentType("text/html");
Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
cookie.setDomain(SSORealm.SSO_DOMAIN);
cookie.setMaxAge(-1);
cookie.setPath("/");
cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookie);

Which expires the cookie when the browser is closed as per the documentation . 根据文档关闭浏览器时 cookie 会过期。

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits.负值表示 cookie 不会永久存储,并且会在 Web 浏览器退出时被删除。 A zero value causes the cookie to be deleted.零值会导致 cookie 被删除。

The full working snippet to expire a cookie is:使 cookie 过期的完整工作片段是:

//remove single signon cookie if it hasn't been validated yet
response.setContentType("text/html");
Cookie cookie = new Cookie(SSORealm.SSO_COOKIE_NAME, "");
cookie.setDomain(SSORealm.SSO_DOMAIN);
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookie);

The MaxAge of -1 signals that you want the cookie to persist for the duration of the session. MaxAge 为 -1 表示您希望 cookie 在会话期间持续存在。 You want to set MaxAge to 0 instead.您希望将 MaxAge 设置为 0。

From the API documentation :API 文档

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. 负值表示 cookie 不会持久存储,将在 Web 浏览器退出时删除。 A zero value causes the cookie to be deleted. 零值会导致 cookie 被删除。

In my environment, following code works.在我的环境中,以下代码有效。 Although looks redundant at first glance, cookies[i].setValue("");虽然乍一看看起来多余, cookies[i].setValue(""); and cookies[i].setPath("/");cookies[i].setPath("/"); are necessary to clear the cookie properly.需要正确清除cookie。

private void eraseCookie(HttpServletRequest req, HttpServletResponse resp) {
    Cookie[] cookies = req.getCookies();
    if (cookies != null)
        for (Cookie cookie : cookies) {
            cookie.setValue("");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }
}

Keep in mind that a cookie is actually defined by the tuple of it's name, path, and domain.请记住,cookie 实际上是由它的名称、路径和域的元组定义的。 If any one of those three is different, or there is more than one cookie of the same name, but defined with paths/domains that may still be visible for the URL in question, you'll still see that cookie passed on the request.如果这三个中的任何一个不同,或者有多个相同名称的 cookie,但定义的路径/域对于相关 URL 可能仍然可见,您仍然会看到该 cookie 在请求中传递。 Eg if the url is " http://foo.bar.com/baz/index.html ", you'll see any cookies defined on bar.com or foo.bar.com, or with a path of "/" or "/baz".例如,如果 url 是“ http://foo.bar.com/baz/index.html ”,您将看到在 bar.com 或 foo.bar.com 上定义的任何 cookie,或者路径为“/”或“/巴兹”。

Thus, what you have looks like it should work, as long as there's only one cookie defined in the client, with the name "SSO_COOKIE_NAME", domain "SSO_DOMAIN", and path "/".因此,只要客户端中只定义了一个 cookie,名称为“SSO_COOKIE_NAME”、域“SSO_DOMAIN”和路径“/”,您所拥有的看起来应该可以工作。 If there are any cookies with different path or domain, you'll still see the cookie sent to the client.如果有任何具有不同路径或域的 cookie,您仍然会看到发送到客户端的 cookie。

To debug this, go into Firefox's preferences -> Security tab, and search for all cookies with the SSO_COOKIE_NAME.要对此进行调试,请进入 Firefox 的首选项 -> 安全选项卡,然后搜索所有带有 SSO_COOKIE_NAME 的 cookie。 Click on each to see the domain and path.单击每个以查看域和路径。 I'm betting you'll find one in there that's not quite what you're expecting.我敢打赌你会在那里找到一个与你期望的不太一样的。

Cookie[] cookies = request.getCookies();
if(cookies!=null)
for (int i = 0; i < cookies.length; i++) {
 cookies[i].setMaxAge(0);
}

did that not worked?那没有用吗? This removes all cookies if response is send back.如果响应被发回,这将删除所有 cookie。

This is code that I have effectively used before, passing "/" as the strPath parameter.这是我之前有效使用的代码,将"/"作为 strPath 参数传递。

public static Cookie eraseCookie(String strCookieName, String strPath) {
    Cookie cookie = new Cookie(strCookieName, "");
    cookie.setMaxAge(0);
    cookie.setPath(strPath);

    return cookie;
}

The proper way to remove a cookie is to set the max age to 0 and add the cookie back to the HttpServletResponse object.删除 cookie 的正确方法是将最大年龄设置为 0 并将 cookie 添加回 HttpServletResponse 对象。

Most people don't realize or forget to add the cookie back onto the response object.大多数人没有意识到或忘记将 cookie 添加回响应对象。 By doing that it will expire and remove the cookie immediately.通过这样做,它将立即过期并删除 cookie。

...retrieve cookie from HttpServletRequest
cookie.setMaxAge(0);
response.addCookie(cookie);

One special case: a cookie has no path.一种特殊情况:cookie 没有路径。

In this case set path as cookie.setPath(request.getRequestURI())在这种情况下,将路径设置为cookie.setPath(request.getRequestURI())

The javascript sets cookie without path so the browser shows it as cookie for the current page only. javascript 设置没有路径的 cookie,因此浏览器仅将其显示为当前页面的 cookie。 If I try to send the expired cookie with path == / the browser shows two cookies: one expired with path == / and another one with path == current page .如果我尝试使用path == /发送过期的 cookie,浏览器会显示两个 cookie:一个使用path == /过期,另一个使用path == current page

When a cookie passed from client to server, it only contains key/value pair, nothing else.当一个cookie从客户端传递到服务器时,它只包含键/值对,没有别的。 which means, when sever receives cookie, it doesn't know这意味着,当服务器收到 cookie 时,它​​不知道

  • if this cookie is http-only如果这个 cookie 是 http-only
  • if this cookie is secure如果这个 cookie 是安全的
  • this cookie's domain此 cookie 的域
  • this cookie's path这个 cookie 的路径

so you may have to manually set domain and path according to the cookie's domain and path in Chrome developer panel.因此您可能需要在 Chrome 开发者面板中根据 cookie 的域和路径手动设置域和路径。

Let's say you have a cookie:假设你有一个 cookie:

  • key = dummy-cookie关键 = 虚拟饼干

  • value = dummy-value值 = 虚拟值

  • domain = .bar.com域 = .bar.com

  • path = / then, if you write sever code like this, it won't work: path = / 那么,如果你这样写服务器代码,它就行不通了:

     cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); resp.addCookie(cookie);

because when expoler receives your response, it will match the set-cookie header with local cookies by name, path and domain.因为当 expoler 收到您的响应时,它将按名称、路径和域将 set-cookie 标头与本地 cookie 匹配。

following code works:以下代码有效:

        cookie.setValue("");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        cookie.setDomain(".bar.com");
        cookie.setPath("/");
        resp.addCookie(cookie);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM