java 在同一个响应中设置多个 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13052565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting several cookies in same response
提问by Duveit
I need to create several persistentcookies in one response.
我需要在一个响应中创建多个持久性cookie。
Doing it like
这样做
response.addCookie(new Cookie("1","1"));
response.addCookie(new Cookie("2","2"));
would create a response with 2 "Set-Cookie" headers. But they wouldn't be persistent. I need "expires" date for that.
将创建一个带有 2 个“Set-Cookie”标头的响应。但他们不会执着。我需要“到期”日期。
expires=Wed, 07-Nov-2012 14:52:08 GMT
Seeing how javax.servlet.http.Cookie doesn't support "expires", I've previously used
看到 javax.servlet.http.Cookie 如何不支持“过期”,我以前用过
String cookieString="cookieName=content;Path=/;expires=Wed, 07-Nov-2012 14:52:08 GMT;"
response.setHeader("Set-Cookie", cookieString);
Which works like a charm, but using response.setHeader("Set-Cookie",newCookie) a second time, would overwrite the first one.
这就像一个魅力,但第二次使用 response.setHeader("Set-Cookie",newCookie) 会覆盖第一个。
So, the question is if there any way to add several identical named headers to the response? Or if there is any other correct way of doing this?
那么,问题是有没有办法在响应中添加几个相同命名的标头?或者是否还有其他正确的方法可以做到这一点?
I've seen suggestions using comma separated cookies, but my experience is that only the first cookie gets read by the browser.
我见过使用逗号分隔 cookie 的建议,但我的经验是浏览器只会读取第一个 cookie。
回答by BalusC
You need addHeader()
instead of setHeader()
. The former addsa header while the latter sets(and thus overrides any old one) a header.
你需要addHeader()
而不是setHeader()
. 前者添加一个标题,而后者设置(从而覆盖任何旧的)标题。
response.addHeader("Set-Cookie", cookieString1);
response.addHeader("Set-Cookie", cookieString2);
The proper way, however, is to use setMaxAge()
method of the Cookie
class (which takes the expire time in seconds) and use addCookie()
the usual way.
然而,正确的方法是使用类的setMaxAge()
方法Cookie
(以秒为单位获取过期时间)并使用addCookie()
通常的方法。
Cookie cookie1 = new Cookie("1","1");
cookie1.setMaxAge(1209600);
response.addCookie(cookie1);
Cookie cookie2 = new Cookie("2","2");
cookie2.setMaxAge(1209600);
response.addCookie(cookie2);