21

I have a JSF form over a JSF 1.2 Session Scope Bean. I have a "Reset" button which invalidates the session.

I tried to use cookies to remember a session number (Not JSF session but my private session number) between sessions but I failed. My question - Where is the correct place (Some listener? Bean Constructor?) to initialize, retrieve and store the cookie.

Looking for the best method to do this.

Thanks!

Ben
  • 10,020
  • 21
  • 94
  • 157

1 Answers1

35

You can obtain all cookies by ExternalContext#getRequestCookieMap()

Map<String, Object> cookies = externalContext.getRequestCookieMap();
// ...

When running JSF on top of Servlet API (which is true in 99.9% of the cases ;) ), the map value resolves to javax.servlet.http.Cookie.

Cookie cookie = (Cookie) cookies.get(name);
// ...

In JSF 1.2, which lacks the JSF 2.0-introduced ExternalContext#addResponseCookie() method, you need to cast the ExternalContext#getResponse() to HttpServletResponse (only when running JSF on top of Servlet API of course) and then use the HttpServletResponse#addCookie().

HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
Cookie cookie = new Cookie(name, value);
cookie.setMaxAge(maxAge); // Expire time. -1 = by end of current session, 0 = immediately expire it, otherwise just the lifetime in seconds.
response.addCookie(cookie);

You can do this anywhere in the JSF context you want, the right place depends on the sole functional requirement. You only need to ensure that you don't add the cookie when the response has already been committed, it would otherwise result in an IllegalStateException.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • The method `addResponseCookie()` accepts the parameters `String name, String value, Map properties`. I assume that e.g. _maxAge_ of `javax.servlet.http.Cookie` are encoded in the properties. Is there a way to use a `Cookie` directly? – Thor Aug 04 '12 at 14:27
  • Click the `addResponseCookie()` link in my answer. It points to the javadoc. – BalusC Aug 04 '12 at 14:36
  • @BalusC, do i have to get all the cookies to get a specific cookie, can't i get a specific cookie directly ? – Mahmoud Saleh Nov 07 '12 at 08:28
  • 1
    @Mahmoud: you're talking about the `getRequestCookieMap()`? I'm not sure how exactly that forms a problem. The cookies are already been parsed and collected in the map beforehand. This does not happen everytime. If you'd like more convenient methods, you could look at `Faces#getRequestCookie()` method of [OmniFaces](http://code.google.com/p/omnifaces/). – BalusC Nov 07 '12 at 10:40