tags:

views:

513

answers:

2

I'm a .Net developer starting to dabble in Java. I have a simple question concerning cookies. In .Net, I can set the value of a cookie to a string with white space in it - new HttpCookie("myCookieName", "my value") - and when I read that value on the client side (javascript), I get the value I expected (my value). If I do the same thing in java - new Cookie("myCookieName", "my value") - I get the value including the double quotes ("my value"). Why the difference? Am I missing something? How do people handle this in the java world? Do you encode the value and then you decode on the client side?

+1  A: 

It probably has to do with the way Java encodes the cookie. I suggest you try calling setVersion(1) on the new cookie and see if that works for you.

Randolpho
+2  A: 

As far as I know, spaces must be encoded in cookies. Different browsers react differently to un-encoded cookies. You should URL-encode your cookie before setting it.

String cookieval = "my value";
String cookieenc = URLEncoder.encode(cookieval, "UTF-8");
res.addCookie(new Cookie("myCookieName", cookieenc));

ASP.NET does the encoding automatically, in Java you have to do it yourself. I suspect the quotes you see are added by the user agent.

Tomalak