沒有'Guice way'來添加會話監聽器。可悲的是。但從會話偵聽器訪問servlet上下文沒有問題。
註冊會話監聽器:
public class MyServletConfig extends GuiceServletContextListener {
private Injector injector;
@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
injector = Guice.createInjector(new MyAppModule());
registerSessionListeners(servletContextEvent.getServletContext(), injector);
super.contextInitialized(servletContextEvent);
}
private void registerSessionListeners(final ServletContext servletContext, final Injector injector) {
servletContext.addListener(injector.getInstance(WebsocketCloser.class));
}
@Override
protected Injector getInjector() {
return injector;
}
}
訪問servlet上下文是會話監聽器:
public class WebsocketCloser implements HttpSessionListener {
@Override
public void sessionCreated(final HttpSessionEvent httpSessionEvent) {
// no-op
}
@Override
public void sessionDestroyed(final HttpSessionEvent httpSessionEvent) {
// do cleanup: httpSessionEvent.getSession().getServletContext();
}
}