注册的web.xml听众我使用吉斯和吉斯的servlet在我的项目。 我可以在一个servlet模块使用的服务(...)和过滤器(...)方法映射servlet和过滤器。 如何在servlet模块中注册监听器(web.xml中的监听器标签)。 我正在使用HttpSessionAttributeListener。使用吉斯的servlet模块
我想使用的吉斯注射器在我的听众。我尝试使用bindListener(..),但似乎没有工作。
问候
注册的web.xml听众我使用吉斯和吉斯的servlet在我的项目。 我可以在一个servlet模块使用的服务(...)和过滤器(...)方法映射servlet和过滤器。 如何在servlet模块中注册监听器(web.xml中的监听器标签)。 我正在使用HttpSessionAttributeListener。使用吉斯的servlet模块
我想使用的吉斯注射器在我的听众。我尝试使用bindListener(..),但似乎没有工作。
问候
基于吉斯documentation,ServletModule
仅用于配置servlet和过滤器。
This module sets up the request and session scopes, and provides a place to configure your filters and servlets from.
所以你的情况你有你的监听器添加到您的web.xml
,并以某种方式获取注射器。
我能想到的几个选项。
(1)正常注册监听器(在web.xml中),并从servlet上下文属性中检索注入器。 GuiceServletContextListener
把喷油器的实例在servlet上下文与Injector.class.getName()
属性名初始化之后。我不确定这是否被记录或支持,所以你可能想要为注入器定义自己的属性名称并将其放置在那里。只要确保你说明了监听器的初始化顺序 - 注入器不会被绑定,直到你的GuiceServletContextListener被调用。
class MyListenerExample implement HttpSessionListener { // or whatever listener
static final String INJECTOR_NAME = Injector.class.getName();
public void sessionCreated(HttpSessionEvent se) {
ServletContext sc = se.getSession().getServletContext();
Injector injector = (Injector)sc.getAttribute(INJECTOR_NAME);
// ...
}
}
(2)如果你使用Java servlet API 3.0或更新版本,您可以调用ServletContext的addListener
。我可能会建议你在创建注射器时做对,尽管你可以在任何地方做到。这种方法对我来说有点不好意思,但应该工作。
public class MyServletConfig extends GuiceServletContextListener {
ServletContext servletContext;
@Override
public void contextInitialized(ServletContextEvent event) {
servletContext = event.getServletContext();
// the super call here is where Guice Servlets calls
// getInjector (below), binds the ServletContext to the
// injector and stores the injector in the ServletContext.
super.contextInitialized(event);
}
@Override
protected Injector getInjector() {
Injector injector = Guice.createInjector(new MyServletModule());
// injector.getInstance(ServletContext.class) <-- won't work yet!
// BIND HERE, but note the ServletContext will not be in the injector
servletContext.addListener(injector.getInstance(MyListener.class));
// (or alternatively, store the injector as a member field and
// bind in contextInitialized above, after the super call)
return injector;
}
}
请注意,在上述所有组合中,监听器不保证在GuiceFilter管道中调用。所以,特别是,虽然它可能有效,但我建议您不要依赖对侦听器中的请求范围对象的访问,包括HttpServletRequest和HttpServletResponse。
非常有帮助!就我的情况而言''getInjector()'在'contextInitialized()'之前被调用。这有点奇怪,但仍然有效! – lfx 2013-08-26 08:29:05