In my Java EE 6-webapp (running on latest GlassFish 3.1), I’m using JSF2-ManagedBeans and @ManagedProperty to inject them into other ManagedBeans. Now i would like to know if i can also inject a @ManagedBean into a @WebServlet, using @ManagedProperty. Some code:
@WebServlet(name = "vdd")
public class VddServlet extends HttpServlet
{
@ManagedProperty(value = "#{userIdentity}")
private UserIdentity identity;
}
The ManagedBean looks like this:
@ManagedBean
public class UserIdentity
{
...
}
Does it work like this? If not, what other ways do i have to inject a ManagedBean into a WebServlet (without CDI, which is currently not an option – since there are some issues in GF 3.1 B32/33 in combination with OSGi-Java EE-apps, but we are short on time)?
Using
@ManagedPropertyin a servlet is not possible since this works in@ManagedBeanclasses only. Further, injecting an object which has a lesser scope than the parent itself is also not possible since that would also only end up in concurrency problems. The injector would throw a runtimeexception for that. A servlet is in essence application scoped and shared among all users and yourUserIdentitybean seems to be session scoped.Since JSF runs on top of the Servlet API and stores the session scoped beans in, well, the session, you could in the servlet just grab it as session attribute:
Note that the
FacesContextis usually also not available in a servlet other thanFacesServlet, so usingFacesContextin the servlet as suggested in a comment does not make any sense, that would only returnnull.