Совместное использование файлов cookie поддоменов - PullRequest
1 голос
/ 11 февраля 2012

У меня есть домен «www.foo.com», и я хочу создать поддомен «test.foo.com». Чтобы объединить эти два домена и использовать только один файл cookie, я настроил этот файл cookie следующим образом:

Cookie cookie = new Cookie("myCookie", "myValue");
cookie.setMaxAge(60 * 60);
cookie.setDomain(".foo.com");

Таким образом, теперь будет только один файл cookie: «foo.com», и значения будут сохранены в том же файле cookie. Проблема для старых пользователей, для них будет два куки («www.foo.com» и «foo.com»), как я могу объединить эти два куки в один ??

Еще одна вещь, пользователи сайта «test.foo.com» в конечном итоге посетят сайт «www.foo.com» и наоборот.

1 Ответ

1 голос
/ 11 февраля 2012

Получить старый cookie из запроса сервлета http, затем установить его максимальный возраст 0. Это побудит клиентскую сторону избавиться от него (в свое время, обычно сразу).Также смотрите Javadoc на Cookie .

<h3>setMaxAge</h3>

public void setMaxAge(int expiry)
Sets the maximum age in seconds for this Cookie.
A positive value indicates that the cookie will expire after that many seconds
have passed. Note that the value is the maximum age when the cookie will expire,
not the cookie's current age.

A negative value means that the cookie is not stored persistently and will be
deleted when the Web browser exits. A zero value causes the cookie to be deleted.

<i>Parameters:</i>
<b>expiry</b> - an integer specifying the maximum age of the cookie in seconds; 
   if negative, means the cookie is not stored; if zero, deletes the cookie
<i>See Also:</i>
getMaxAge()

. Вам нужно будет проанализировать ваши куки и найти тот, от которого вы пытаетесь избавиться.Как то так:

final Cookie[] cookies = request.getCookies();
for(Cookie cookie: cookies) {
    if("www.foo.com".equals(cookie.getDomain()) cookie.setMaxAge(0);
}
...