【问题标题】:setting cookie to null not working in java将cookie设置为null在java中不起作用
【发布时间】:2014-11-21 05:52:41
【问题描述】:

我想删除在我的云服务器中运行的域名和上下文路径为“/”的 cookie。

我有以下代码用于清除云服务器中的 cookie

    Cookie cookie = new Cookie(cookieName, null);// cookieName = TEST_COOKIE
    String cookiePath = request.getContextPath();
    cookie.setPath(cookiePath); // path = "/"
    cookie.setDomain("mydomain.com");
    cookie.setMaxAge(0);
    response.addCookie(cookie);

如果我注意到浏览器中的 cookie,我有以下详细信息

cookie name = "TEST_COOKIE"  value  = "MUZJd3NuNDhy"  domain = "mydomain.com" path = "/"

在我的本地主机中,上面的代码可以正常工作,无需设置域名。即使我尝试使用无效的空域名。不知道如何进行,非常感谢方向。

编辑 - 下面的 localhost 中没有域的代码在上下文路径作为 /MyApp 的情况下工作正常。

    Cookie cookie = new Cookie(cookieName, null);
    String cookiePath = request.getContextPath();
    cookie.setPath(cookiePath); // path = "/"
    cookie.setMaxAge(0);
    response.addCookie(cookie);

当我删除 contextPath "/MyApp" 时,它也停止在 localhost 中工作,在我的云服务器中,我的上下文路径是 "/"。

【问题讨论】:

  • 您是否尝试过设置非空值,但仍然使用setMaxAge(0)

标签: java html cookies session-cookies setcookie


【解决方案1】:

您不能将Cookie 设置为null,但可以将其删除(即:当您下次尝试获取它时,它将返回 null)。

只需将您的第一行更改为:

Cookie cookie = new Cookie(cookieName, "");
String cookiePath = request.getContextPath();
cookie.setPath(cookiePath); // path = "/"
cookie.setDomain("mydomain.com");
cookie.setMaxAge(0);
response.addCookie(cookie);

【讨论】:

  • 不工作的伙伴..这段代码在本地工作,但在云中不工作
【解决方案2】:

经过大量调试,我发现request.getContextPath 在我的远程服务器和jave doc 中返回空字符串而不是“/”

 * Returns the portion of the request URI that indicates the context
 * of the request. The context path always comes first in a request
 * URI. The path starts with a "/" character but does not end with a "/"
 * character. For servlets in the default (root) context, this method
 * returns "". The container does not decode this string.

因为我有根上下文,该方法返回空字符串而不是“/”,我已经通过下面的代码修复了它,它现在可以工作了。

    if (cookiePath.isEmpty()) {
        cookie.setPath("/");
    } else {
        cookie.setPath(cookiePath);
    }

【讨论】:

    猜你喜欢
    • 2014-11-18
    • 1970-01-01
    • 2019-08-01
    • 2013-07-10
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多