Search code examples
javajsfservletsmanaged-bean

How to register a JSF managed bean programmatically?


I'd like to register/add a Managed Bean class programmatically (from within a Servlet init()) into application scope. How can I do that with JSF 1.2?


Solution

  • from within a Servlet init()

    So, it concerns a non-JSF request. The FacesContext#getCurrentInstance() would return null here, so it's of no use for you here.

    It's good to know that JSF application scoped managed beans are basically stored as an attribute of the ServletContext. In the init() method you've the ServletContext at your hands by the inherited getServletContext() method. So, the following should do:

    @Override
    public void init() {
        getServletContext().setAttribute("managedBeanName", new BackingBean());
    }
    

    That's it. It'll be available in JSF by #{managedBeanName}.