Sometimes you need the FacesContext.getCurrentInstnace() in a servlet, that is no a FacesServlet, e.g. when passing a URL to the FILEDOWNLOAD* components.
Code:
package org.eclnt.jsfserver.bufferedcontent;
import java.io.IOException;
import javax.faces.FactoryFinder;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.eclnt.util.log.CLog;
public class BufferedContentServlet extends HttpServlet
{
// ------------------------------------------------------------------------
// members
// ------------------------------------------------------------------------
private FacesContextFactory m_facesContextFactory;
private Lifecycle m_lifecycle;
// ------------------------------------------------------------------------
// public usage
// ------------------------------------------------------------------------
@Override
public void init() throws ServletException
{
super.init();
try
{
LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
m_facesContextFactory = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
m_lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
}
catch (Throwable t)
{
CLog.L.log(CLog.LL_INF,"Problems in init() of BufferedContentServlet - only relevant if accessing FacesContext during servlet processing",t);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// create faces context
FacesContext context = null;
try
{
context = m_facesContextFactory.getFacesContext(getServletContext(),req,resp,m_lifecycle);
}
catch (Throwable t)
{
CLog.L.log(CLog.LL_INF,"Problems in init() of BufferedContentServlet - only relevant if accessing FacesContext during servlet processing",t);
}
...
...
...
normal servlet processing
...
...
...
// clean up
if (context != null)
{
context.release();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
doGet(req,resp);
}
}
I am not 100% sure is this is a "hack"... Of course you need to be aware that all the typical things like JSF request lifecylcle etc. are not executed... But maybe you require the context for the resolution of some value bindings.
Björn