我有一个域'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中。 问题出在旧用户身上,对于他们来说会有两个cookie('www.foo.com'和'foo.com'),如何将这两个cookie合并为一个?
还有一件事,来自'test.foo.com'的用户最终将访问'www.foo.com',反之亦然。
答案 0 :(得分:1)
从http servlet请求获取旧cookie,然后将其最大年龄设置为0.这将触发客户端摆脱它(在其自己的时间,通常是立即)。另请参阅Cookie上的Javadoc。
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()
您需要解析Cookie并搜索您要删除的Cookie。像这样:
final Cookie[] cookies = request.getCookies();
for(Cookie cookie: cookies) {
if("www.foo.com".equals(cookie.getDomain()) cookie.setMaxAge(0);
}