Wednesday, January 18, 2012

How-to: "Servlet access to JSF context" or "Accessing a JSF managedBean from a Servlet"

There have been several posts asking how to get a Faces Context or Faces managed bean from outside of JSF such as in a servlet.

After obtaining Faces Context from servlet or filter, you can:
  • access managed beans in application or session scope from your custom servlet or servlet filter
  • get or set the current view id
  • perform authentication and session management
  • generate additional content to be displayed in a faces component
  • and so on
There is in the web many better and worse solutions of this dilema. My approach bases on my custom JSF util library, which is available to download from SourceForge. LikaonJsfUtil.jar provides functionalities we can use to solve our issue.
Class AbstractFacesServlet provides extra methods to establish communication between our custom server and Faces Controller:

protected javax.faces.context.FacesContext getFacesContext(javax.servlet.http.HttpServletRequest request, 

javax.servlet.http.HttpServletResponse response);

protected javax.faces.application.Application getApplication(javax.faces.context.FacesContext ctx);

protected java.lang.Object getManagedBean(java.lang.String beanName, javax.faces.context.FacesContext ctx);

The AbstractServletRequestWrapper class we can use in our filters also provides simillar methods.

How to use cited classes:

public class FileUploadServlet extends AbstractFacesServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

    public void init(ServletConfig config) throws ServletException {

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException, IOException {
        /* Bean ApplicationBean1 is application scope bean registered in faces-config .xml or via annotation*/
        ApplicationBean1 myBean = (ApplicationBean1) this.getManagedBean("ApplicationBean1", this.getFacesContext(request, response));
        /* and so on */


1 comment: