timmornYE
timmornYE

Reputation: 728

@WebFilter and FacesContext.getCurrentInstance() -> Nullpointer

In my application I have a WebFilter. This Webfilter should check a coockie. But the use of FacesContext.getCurrentInstance() gives a Nullpointer exception. How can I solve this?

The WebFilter:

@Inject
private CookieManager cm;   

[...]

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if(cm.isDoCheck()){
        cm.doCheck();
    }
    chain.doFilter(request, response);
}
[...]

The CookieManager which does the FacesContext.getCurrentInstance():

[...]
private void doCheck(){
    FacesContext context = FacesContext.getCurrentInstance();
    Map<String, Object> cookies = context.getExternalContext().getRequestCookieMap();

    Cookie cookie = (Cookie) cookies.get("frontend");
    if(cookie != null){
        setSessionHash(cookie.getValue());
    }
}
[...]

context.getExternalContext().getRequestCookieMap(); gives the

StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException

Upvotes: 4

Views: 2338

Answers (1)

BalusC
BalusC

Reputation: 1108742

The FacesContext is created by FacesServlet. Any servlet filter is invoked before any servlet. The FacesContext is therefore per definition not available in any servlet filter.

As to the concrete functional requirement of grabbing the request cookies, you also seem to have completely missed the fact that FacesContext is a facade of among others the ServletRequest and ServletResponse. The methods of ExternalContext all delegate under the covers to ServletRequest/ServletResponse methods (this is clearly mentioned in its javadoc, for example getRequestCookieMap()). The cookie methods you need is just readily available via ServletRequest argument of the doFilter() method.

HttpServletRequest hsr = (HttpServletRequest) request;
Cookie[] cookies = hsr.getCookies();
// Loop over cookies to find the one matching the name.

Noted should be that there is a hack/workaround available to create FacesContext in the filter yourself based on ServletRequest and ServletResponse variables, but this makes after all no utter sense if the information is readily available in those variables themselves.

I suggest to take a little JSF pause and learn basic Servlet API as well. That's basically what JSF is using under the covers (you see, its FacesServlet is "just" a servlet). Reading the method descriptions in the ExternalContext javadoc should also hint you where exactly in the basic Servlet API all those methods are getting their information from.

Upvotes: 5

Related Questions