How to use cookies in JSF

后端 未结 1 941
暖寄归人
暖寄归人 2021-02-01 06:26

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 JS

相关标签:
1条回答
  • 2021-02-01 06:56

    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.

    0 讨论(0)
提交回复
热议问题