This is from http://jsffaq.com. Currentyle the site is down. I`ve
downloaded this article before.
---------------
Outside the Faces realm, for example in a filter or a servlet, when
the FacesContent.getCurrentInstance() returns null, you can use
FacesContextFactory to reach the FacesContext. This is a method that
allows you to do so:
// You need an inner class to be able to call FacesContext.setCurrentInstance
// since it's a protected method
private abstract static class InnerFacesContext extends FacesContext
{
protected static void setFacesContextAsCurrentInstance(FacesContext
facesContext) {
FacesContext.setCurrentInstance(facesContext);
}
}
private FacesContext getFacesContext(ServletRequest request,
ServletResponse response) {
// Try to get it first
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) return facesContext;
FacesContextFactory contextFactory =
(FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
LifecycleFactory lifecycleFactory =
(LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle =
lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
// Either set a private member servletContext =
filterConfig.getServletContext();
// in you filter init() method or set it here like this:
// ServletContext servletContext =
((HttpServletRequest)request).getSession().getServletContext();
// Note that the above line would fail if you are using any other
protocol than http
// Doesn't set this instance as the current instance of
FacesContext.getCurrentInstance
facesContext = contextFactory.getFacesContext(servletContext,
request, response, lifecycle);
// Set using our inner class
InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
// set a new viewRoot, otherwise context.getViewRoot returns null
UIViewRoot view =
facesContext.getApplication().getViewHandler().createView(facesContext,
"yourOwnID");
facesContext.setViewRoot(view);
return facesContext;
}
--
Seeing is believing