---
title: "Response Header Set-Cookie difference in cross browser"
author: "cuishen"
date: "2014-07-02T21:26:07Z"
tags: []
categories: ["企业架构"]
slug: "response-header-set-cookie-difference-in-cross-browser"
draft: false
lastmod: "2014-07-05T09:40:13Z"
id: 2087734
url: "https://cuishen.iteye.com/blog/2087734"
---

如果你项目中需要在server端把cookie写回client端，例如在JSP中写下面的代码：

```java

<%
Cookie cookie = new Cookie("testCookie", "testValue");
cookie.setMaxAge(60);
cookie.setPath("/");
response.addCookie(cookie);
%>

```

会有下面的信息在response header里面：

```java

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”，能很好的解决这个问题：

如下代码：

```java

response.addHeader("Set-Cookie", "testCookie2=test2; Max-Age=60; Path=/");

```

response header 如下：

```java

Set-Cookie	testCookie2=test2; Max-Age=60; Path=/

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