Get Cookies from ServletRequest

Ben picture Ben · Mar 24, 2011 · Viewed 14k times · Source

I'm using ServletRequestListener to attach to new requests, get a ServletRequest object and extract cookies from it.

I've noticed that only HTTPServletRequest has cookies but I haven't found a connection between those two objects.

Is it okay to use

HttpServletRequest request = ((HttpServletRequest) FacesContext.getCurrentInstance()
                .getExternalContext().getRequest());

to retrieve the request while in a RequestInitialized method? (I do want to run on every request)

FYI - This is all done in a JSF 1.2 Application

Answer

BalusC picture BalusC · Mar 24, 2011

This is not correct. The FacesContext isn't available in a ServletRequestListener per se. The getCurrentInstance() might return null, leading to NPE's.

If you're running the webapp on a HTTP webserver (and thus not some Portlet webserver for example), you could just cast the ServletRequest to HttpServletRequest.

public void requestInitialized(ServletRequestEvent event) {
    HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
    // ...
}

Note that a more common practice is to use a Filter for this since you can map this on a fixed URL pattern like *.jsf or even on specific servlets so that it runs only when the FacesServlet runs. You might for example want to skip cookie checks on static resources like CSS/JS/images.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    HttpServletRequest request = (HttpServletRequest) req;
    // ...
    chain.doFilter(req, res);
}

When you happens to be already inside the JSF context (in a managed bean, phaselistener or whatever), you could just use ExternalContext#getRequestCookieMap() to get the cookies.

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

When running JSF on top of Servlet API, the map value is of type javax.servlet.http.Cookie.

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