Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to inject @ManagedBean as a @ManagedProperty into @WebServlet?

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)?

like image 631
Wolkenarchitekt Avatar asked Dec 17 '10 09:12

Wolkenarchitekt


1 Answers

Using @ManagedProperty in a servlet is not possible since this works in @ManagedBean classes 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 your UserIdentity bean 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:

UserIdentity identity = (UserIdentity) request.getSession().getAttribute("userIdentity");

Note that the FacesContext is usually also not available in a servlet other than FacesServlet, so using FacesContext in the servlet as suggested in a comment does not make any sense, that would only return null.

like image 123
BalusC Avatar answered Sep 27 '22 22:09

BalusC