设置域cookie麻烦

时间:2014-03-20 06:37:41

标签: java servlets cookies httpresponse

我正在尝试设置Cookie的域名。但它不起作用,我的cookie不会在此之后创建:

    javax.servlet.http.Cookie responseCookie =
        new Cookie(startpackCookie.getName(),
                   startpackCookie.getValue());

    responseCookie.setMaxAge(startpackCookie.getMaxAge());
    responseCookie.setPath(startpackCookie.getPath());
    responseCookie.setDomain(startpackCookie.getDomain());

    System.out.println("Cookie max age: " +
                       responseCookie.getMaxAge());
    System.out.println("Cookie path: " + responseCookie.getPath());
    System.out.println("Cookie domain: " + responseCookie.getDomain());
    response.addCookie(responseCookie);

输出:

10:28:34,899 INFO  [stdout] (http-/127.0.0.1:8080-5) Cookie max age: -1
10:28:34,900 INFO  [stdout] (http-/127.0.0.1:8080-5) Cookie path: /
10:28:34,900 INFO  [stdout] (http-/127.0.0.1:8080-5) Cookie domain: playground.startpack.ru
10:28:34,901 INFO  [stdout] (http-/127.0.0.1:8080-5) Cookie was sended

如果我要删除域名设置,则可以使用localhost域名。怎么了?

1 个答案:

答案 0 :(得分:1)

来自Sun的网站, “默认情况下,cookie只会返回给保存它们的主机。”

http://java.sun.com/products/servlet/2.1/api/javax.servlet.http.Cookie.html#setDomain(javax.servlet.http.String)

域名也以点(“.foo.com”)开头,对指定域名系统(DNS)区域中的服务器可见(例如,www.foo.com,但不是abfoo.com)