Search code examples
httpservletscookiesquotes

How to create cookie without quotes around value?


I need to create cookie with e-mail address as value - but when I try to - then I have result:

"[email protected]"

but I would like to have:

[email protected]

The cookie should be created without double quoted marks - because other application uses it in such format. How to force java to not to add double quoted? Java adds them because there is special char "at".

I create the cookie that way:

    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    Cookie cookie = new Cookie("login", "[email protected]");
    cookie.setMaxAge(2592000);
    cookie.setDomain("domain.com");
    cookie.setVersion(1);
    response.addCookie(cookie);

Thanks for any help.


Solution

  • It's indeed caused by the @ sign. This is not allowed in version 0 cookies. The container will implicitly force it to become a version 1 cookie (which breaks in MSIE browsers). You'd like to URL-encode the cookie value on cookie's creation

    Cookie cookie = new Cookie("login", URLEncoder.encode("[email protected]", "UTF-8"));
    cookie.setMaxAge(2592000);
    cookie.setDomain("domain.com");
    response.addCookie(cookie);
    

    and URL-decode it on cookie reading

    String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
    

    Note that you should for sure not explicitly set the cookie version to 1.

    See also:


    Unrelated to the concrete problem, cookies are visible and manipulatable by the enduser or man-in-the-middle. Carrying the email address around in a cookie is a bad smell. What if the enduser changes it to a different address? Whatever functional requirement (remembering the login?) you thought to solve with carrying the email address around in a cookie should most likely be solved differently.

    See also: