In JSF 2.0 or later it is better to create a custom ResourceHandler wrapper and use FacesServlet instead. In that way, JSF will create FacesContext instance.
If you create a custom FacesContext e.g. like described here Access FacesContext From Servlet you might face a problem that e.g. messages added to your custom FacesContext won't show up in h:messages.
The FacesServlet creates its own new FacesContext which will be used for all subsequent JSF operations.
One reason why this is good is, that the FacesServlet can't be sure that your custom FacesContext use the correct ServletRequest/ServletResponse objects.
An example when your custom FacesContext is not good is when you use requestDispatcher.forward.
Like my setup:
- A custom filter which creates a custom FacesContext
- A custom servlet which forwards to the FacesServlet (getServletContext().getRequestDispatcher(jsfPath).forward(req, res)
- The FacesServlet which creates a FacesContext too
If the FacesServlet uses our own custom FacesContext you will see that JSF did not use the jsfPath for further operations, but the original url - which is false.
So, I found to let the FacesServlet create a new FacesContext is fine and the easiest solution, but I still wanted it to show any messages added to the custom FacesContext.
I ended with the following FacesContextFactory (adjust the package names as needed):
Configuration in faces-config.xml:
Notice: This solution do not deal with resetting to the previousContext on newContext.release(). One can enhance it. For me it was sufficient that way as after the JSF request there is nothing further I will do with the FacesContext ... and the problem might be, that then one might copy some state back ... too complicated.