Injection of HttpServletRequest

Kirill  Bazarov picture Kirill Bazarov · Nov 16, 2012 · Viewed 19k times · Source

I am using ejb 3 and trying to @Inject HttpServletRequest, but while deploying I occur exception.

Code:

@Inject private HttpServletRequest httpRequest;

Exception:

org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [HttpServletRequest] with qualifiers [@Default] at injection point [[field] @Inject private com.kmware.ttk.highway.beans.session.UserSessionBean.httpRequest]

What could I do with that?

Answer

Perception picture Perception · Nov 16, 2012

The lifecycle of HttpServletRequest is managed by the EJB/web container, not the CDI container. Attempting to inject it leads to issues because there are typically many implementations of the interface,and your CDI container does not have enough information to make a decision on which implementation to inject. Even if you successfully injected an instance of it, it would not be the same instance as being managed by the EJB container.

To acquire a properly managed instance of the request, do this instead:

@Context
private HttpServletRequest httpRequest;