choop
choop

Reputation: 921

Sharing sub domain cookies

I have a domain 'www.foo.com' and I want to create sub domain 'test.foo.com'. In order to combine those 2 domains to share only one cookie I set the cookie to be like that:

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

So from now on there will be only one cookie: 'foo.com' and the values will be save on the same cookie. The problem is for old users, for them there will be two cookies ('www.foo.com' and 'foo.com'), how can i merge those two cookies to one??

One more thing, users from 'test.foo.com' eventually will visit 'www.foo.com' and vise versa.

Upvotes: 1

Views: 2237

Answers (1)

Perception
Perception

Reputation: 80603

Get the old cookie from the http servlet request, then set its max age to 0. That will trigger the client side to get rid of it (in its own time, normally right away). Also, see the Javadoc on Cookie.

setMaxAge

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. Parameters: expiry - an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if zero, deletes the cookie See Also: getMaxAge()

You will need to parse through your cookies and search for the one you are trying to get rid of. Something like this:

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

Upvotes: 1

Related Questions