1

I have a servlet filter set up to handle various ways of entering my website. One goal of the filter is to set a cookie on entry. The below code works perfectly in Chrome, Safari and Firefox but IE doesn't seem to like it. Due to some constraints I am not able to set the cookie with JavaScript.

Cookie cookie = new Cookie(COOKIE_NAME, COOKIE_VALUE);
cookie.setPath("/"); //Note: I've tried removing this.
cookie.setDomain(SITE_DOMAIN); //Note: I've tried removing this.
response.addCookie(cookie);

I've tried different combinations of max age and expiration date, but nothing seems to work. I've stepped through on a debugger and I'm sure the code is being executed.

Also, for the record I'm using Tomcat 6. Cookie name and value are both strings of around 10 chars length.

Matt Klooster
  • 717
  • 1
  • 5
  • 13
  • Are you sure the IE you are testing this with does not have cookies turned off all together or uses a very restrictive settings? – joostschouten Dec 20 '12 at 22:31

2 Answers2

2

That will happen when the cookie value contains an illegal character for version 0 cookies, such as white space. With such a cookie value, the average container will automatically switch to version 1 cookies, which is not supported by IE9 or older.

You need to make sure that the cookie value doesn't contain illegal characters for version 0 cookies. This is specified in Cookie#setValue() javadoc as follows:

With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.

If you have no control over the actual cookie value, then your best bet is to URLEncode it before setting and URLDecode it during retrieving.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Good idea, but that wasn't the problem. I'm voting up because I am going use URLEncode and decode regardless, as I've seen the problem you're describing before. – Matt Klooster Dec 21 '12 at 19:44
1

This was actually being caused by a redirect problem. I was redirecting the page on click of a button with

window.location = url;

For some reason this caused IE to make two requests to the server, the first one was aborted according to Fiddler. The server still attempted to handle the first request and set the cookie, but because the request was aborted the browser never set the cookie. Subsequent requests assume the cookie has already been set and doesn't attempt to set it.

Quick work-around was to submit a form with the data rather than adding it to the query string of the URL and redirecting with javascript.

I'm still not sure why IE was making the duplicate request, I'm guessing it was a problem with the javascript maybe being called twice or something.

Matt Klooster
  • 717
  • 1
  • 5
  • 13