Thursday, March 12, 2015

Browser cookie values are not setting in IE10 and IE11

Browser cookie values are not setting in IE10 and IE11

While trying to set the cookies in IE10 and IE11 through Java, the values are not stetting in the browser.

The code snippet used to set the cookie is

cookie = new javax.servlet.http.Cookie(cookieHeaderName,"Sample Cookie");

After long struggle we found the issue might be with the value of Expires is not set, IE10 and IE11 expecting the value for Expires and it is not considering the value set in Max-Age.

Fix for the issue - Use the below code to set the cookie value

int expiration = 365*24*60*60;
StringBuilder cookieString = new StringBuilder("TestCookie=Test; ");

DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, expiration);
cookieString.append("Expires=" + df.format(cal.getTime()) + "; ");
//cookieString.append("Domain="+request.getServerName()+"; ");
cookieString.append("Version=0; ");
cookieString.append("Path=/; ");
cookieString.append("Max-Age=" + expiration + "; ");
response.addHeader("Set-Cookie", cookieString.toString());

No comments:

Post a Comment