在CDI SessionScoped bean中注入HttpServletRequest
我有一个会话范围的CDI bean,我需要以某种方式访问这个bean的@PostConstruct方法中的 HttpServletRequest
对象。可能吗?我试图注入这样一个对象,但结果是:
I've got a session scoped CDI bean, and I need to somehow access the HttpServletRequest
object in this bean's @PostConstruct method. Is it possible? I've tried to Inject such an object, but it results in:
WELD-001408 Unsatisfied dependencies for type [HttpServletRequest] with qualifiers [@Default] at injection point [[field] @Inject ...]
据我了解在谷歌搜索时,Seam框架具有这样的功能,但我在GlassFish服务器上有一个标准的Java EE应用程序。
As I understood while googling, the Seam framework has such a functionality, but I have a standard Java EE application on a GlassFish server.
甚至可以以某种方式将请求传递给CDI bean的 @PostConstruct
方法?
Is it even possible to somehow pass the request to a CDI bean's @PostConstruct
method?
根据你的评论,你想要访问用户主体。您可以像这样注入: @Inject Principal principal;
或 @Resource Principal principal;
,参见 Java EE 6教程。
As per your comment, you want access to the user principal. You can just inject it like this: @Inject Principal principal;
or @Resource Principal principal;
, see Java EE 6 Tutorial.
更新
我会回答您的直接问题。在Java EE 7(CDI 1.1)中,支持开箱即用的HttpServletRequest注入。但是,在Java EE 6(CDI 1.0)中,不支持开箱即用。要使其正常运行,请将以下课程添加到您的网络应用中:
I'll answer your direct question. In Java EE 7 (CDI 1.1) injection of HttpServletRequest is supported out of the box. In Java EE 6 (CDI 1.0) however, this is not supported out of the box. To get it working, include the class below into your web-app:
import javax.enterprise.inject.Produces;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class CDIServletRequestProducingListener implements ServletRequestListener {
private static ThreadLocal<ServletRequest> SERVLET_REQUESTS = new ThreadLocal<>();
@Override
public void requestInitialized(ServletRequestEvent sre) {
SERVLET_REQUESTS.set(sre.getServletRequest());
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
SERVLET_REQUESTS.remove();
}
@Produces
private ServletRequest obtain() {
return SERVLET_REQUESTS.get();
}
}
注意:仅在GlassFish 3.1上测试.2.2
Note: Tested only on GlassFish 3.1.2.2