没有添加会话侦听器的“Guice 方式”。可悲的是。但是从会话侦听器访问 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();
}
}