将cookie设置为null在java中不起作用

将cookie设置为null在java中不起作用,java,html,cookies,session-cookies,setcookie,Java,Html,Cookies,Session Cookies,Setcookie,我想删除在我的云服务器上运行的域名和上下文路径为“/”的cookie 我有下面的代码来清除云服务器中的cookie Cookie cookie = new Cookie(cookieName, null);// cookieName = TEST_COOKIE String cookiePath = request.getContextPath(); cookie.setPath(cookiePath); // path = "/" cookie.setDomai

我想删除在我的云服务器上运行的域名和上下文路径为“/”的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中工作,在我的云服务器中,我的上下文路径是“/”

您不能将
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);

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

 * 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);
    }

您是否尝试过设置非空值,但仍然使用
setMaxAge(0)
?不工作。代码段在本地工作,但在云中不工作