Response Header Set-Cookie difference in cross browser

如果你项目中需要在server端把cookie写回client端,例如在JSP中写下面的代码:
<%
Cookie cookie = new Cookie("testCookie", "testValue");
cookie.setMaxAge(60);
cookie.setPath("/");
response.addCookie(cookie);
%>

会有下面的信息在response header里面:
Set-Cookie	testCookie=testValue; Expires=Wed, 02-Jul-2014 13:01:13 GMT; Path=/


注意,IE下面 和 Chrome / Firefox下面对于“Set-Cookie”的处理是完全不同的,IE是base on client端的时间去计算cookie expire time;
Chrome / Firefox 是base on server端的时间去计算cookie expire time!

So,对于cookie expire过期时间要求很高的场景要特别当心了!

以上面的代码为例:原意是要求cookie在60秒后过期,如果client端比她的local timezone的标准时间快more than 60秒,例如标准时间是10:00:00pm,但是client的system time是10:01:01pm;而server端是她的local timezone的标准时间,那么不管怎么地这个cookie在IE下都是立马过期的!!


--- add some finding:

response header 里的Expires 是指绝对过期时间(server时间),IE是拿这个绝对过期时间和client端的时间比;而正好相反:firefox和Chrome是拿她跟server端的时间比,So 造成了这种behavior上的差异!!

可以在response header里面设置相对过期时间:“Max-Age”,能很好的解决这个问题:

如下代码:
response.addHeader("Set-Cookie", "testCookie2=test2; Max-Age=60; Path=/");

response header 如下:
Set-Cookie	testCookie2=test2; Max-Age=60; Path=/

因为她是相对时间,所以NO matter你的client端的时间是神马,都能确保在Max-Age时间里面能得到cookie!在IE/Firefox/Chrome下测试通过!


猜你喜欢

转载自cuishen.iteye.com/blog/2087734