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. Hi thanks dear. i have resolved my problem.

  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.