Get JSF managed bean by name in any Servlet related class

前端 未结 6 640
难免孤独
难免孤独 2020-11-22 01:33

I\'m trying to write a custom servlet (for AJAX/JSON) in which I would like to reference my @ManagedBeans by name. I\'m hoping to map:

http://host

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:55

    In a servlet based artifact, such as @WebServlet, @WebFilter and @WebListener, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped by:

    Bean bean = (Bean) request.getAttribute("beanName");
    

    and @ManagedBean @SessionScoped by:

    Bean bean = (Bean) request.getSession().getAttribute("beanName");
    

    and @ManagedBean @ApplicationScoped by:

    Bean bean = (Bean) getServletContext().getAttribute("beanName");
    

    Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null. You'd then need to manually create the bean and use setAttribute("beanName", bean).


    If you're able to use CDI @Named instead of the since JSF 2.3 deprecated @ManagedBean, then it's even more easy, particularly because you don't anymore need to manually create the beans:

    @Inject
    private Bean bean;
    

    Note that this won't work when you're using @Named @ViewScoped because the bean can only be identified by JSF view state and that's only available when the FacesServlet has been invoked. So in a filter which runs before that, accessing an @Injected @ViewScoped will always throw ContextNotActiveException.


    Only when you're inside @ManagedBean, then you can use @ManagedProperty:

    @ManagedProperty("#{bean}")
    private Bean bean;
    

    Note that this doesn't work inside a @Named or @WebServlet or any other artifact. It really works inside @ManagedBean only.


    If you're not inside a @ManagedBean, but the FacesContext is readily available (i.e. FacesContext#getCurrentInstance() doesn't return null), you can also use Application#evaluateExpressionGet():

    FacesContext context = FacesContext.getCurrentInstance();
    Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
    

    which can be convenienced as follows:

    @SuppressWarnings("unchecked")
    public static  T findBean(String beanName) {
        FacesContext context = FacesContext.getCurrentInstance();
        return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
    }
    

    and can be used as follows:

    Bean bean = findBean("bean");
    

    See also:

    • Backing beans (@ManagedBean) or CDI Beans (@Named)?

提交回复
热议问题