为什么我的 cookie 总是空的?

Why is my cookie always null?

我不明白。一个小时前它起作用了,突然间我无法取回我刚刚设置的 cookie。在 Chrome 下,我可以看到 cookie 确实存在,但如果我尝试取回它,它是 null:

private void setLoggedInCookie(String sessionId) {
    String domain = this.getDomain();

    Cookies.setCookie(ApiParameters.LOGIN_COOKIE, sessionId, expires, domain, "/", true);
    String cookie = Cookies.getCookie(ApiParameters.LOGIN_COOKIE);

    // Getting NOTHING from this ..
    for (String string : Cookies.getCookieNames()) {
        LOGGER.info("Cookie name: " + string);
    }

    if(cookie == null) {
        throw new RuntimeException("Cookie is 'null'.");
    }
}

private String getDomain() {
    LOGGER.fine("Host name: " + Window.Location.getHostName());
    String domain = Window.Location.getHostName().replaceAll(".*//", "").replaceAll("/", "").replaceAll(":.*", "");
    return "localhost".equalsIgnoreCase(domain) ? "localhost" : domain;
}

发生了什么事?

您传递域名"null"。浏览器只允许访问与当前页面域关联的 cookie。由于您试图从非 "null" 的页面访问它,因此您无法获取它。

此外,请确保您尝试使用 SSL 访问它,因为您将 "secure" 参数设置为 true。