2016-02-28 410 views
0

我不明白这一点。一个小时前,它工作,突然间我无法取回我刚刚设置的cookie。在Chrome浏览器,我可以看到该Cookie实际上是有,但如果我试图把它找回来是null为什么我的cookie始终为空?

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

这是怎么回事?

回答

2

您传递域名“null”。浏览器仅允许访问与当前页面的域相关的cookie。由于您试图从不是“null”的页面访问它,因此您无法获取它。

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

+0

即使我将它设置为'localhost',它也不起作用。就像在我的问题中指出的那样:我可以在Chrome/Firefox设置中看到Cookie,但是我没有从'Cookies.getCookie()'返回。 – displayname

+0

确保您尝试使用SSL访问它,因为您已将其设置为true。注意:你可以随时设置一个cookie - 它对你获得它的能力没有影响。 –

+0

错误是将其设置为安全。我将它从'false'改为'true',并不知道这意味着我必须使用SSL访问它!设置域似乎并不是一个问题,但至少不用于取回它。谢谢! – displayname