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/app/myBean/myProperty
to:
@ManagedBean(name="myBean")
public class MyBean {
public String getMyProperty();
}
Is it possible to load a bean by name from a regular servlet? Is there a JSF servlet or helper I could use for it?
I seem to be spoilt by Spring in which all this is too obvious.
In a servlet based artifact, such as
@WebServlet,@WebFilterand@WebListener, you can grab a "plain vanilla" JSF@ManagedBean @RequestScopedby:and
@ManagedBean @SessionScopedby:and
@ManagedBean @ApplicationScopedby: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 usesetAttribute("beanName", bean).If you’re able to use CDI
@Namedinstead 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:Note that this won’t work when you’re using
@Named @ViewScopedbecause the bean can only be identified by JSF view state and that’s only available when theFacesServlethas been invoked. So in a filter which runs before that, accessing an@Injected@ViewScopedwill always throwContextNotActiveException.Only when you’re inside
@ManagedBean, then you can use@ManagedProperty:Note that this doesn’t work inside a
@Namedor@WebServletor any other artifact. It really works inside@ManagedBeanonly.If you’re not inside a
@ManagedBean, but theFacesContextis readily available (i.e.FacesContext#getCurrentInstance()doesn’t returnnull), you can also useApplication#evaluateExpressionGet():which can be convenienced as follows:
and can be used as follows:
See also: