11

I want to store some user data into a cookie so it's always there when they load the web app, even if the session has expired.

What's the best way of doing this with JSF?

DD.
  • 21,498
  • 52
  • 157
  • 246
  • Cookies may be the wrong approach here. Cookies are for communication from the client to the server. If you want client-side storage, you should maybe look at DOM Storage. – Kerrek SB Jul 20 '11 at 14:15

1 Answers1

20

Writing to a cookie:

FacesContext.getCurrentInstance()
 .getExternalContext()
 .addResponseCookie("CookieName", "value", null);

Reading the cookie

Map<String, Object> requestCookieMap = FacesContext.getCurrentInstance()
   .getExternalContext()
   .getRequestCookieMap();
Brian
  • 13,412
  • 10
  • 56
  • 82
  • 5
    If you're planning on adding properties, you could also use "FacesContext.getCurrentInstance().getExternalContext().getResponse()", cast it to HttpServletResponse, and then use "resp.addCookie(Cookie c)". –  Aug 01 '13 at 17:33
  • 1
    I'm using JSF2.2 and this answer didn't work. If you had the same issue try this answer: http://stackoverflow.com/questions/20934016/how-to-add-cookie-in-jsf – Yamada Aug 28 '14 at 17:05