【问题标题】:How to create listener for spring session destroyed events?如何为春季会话销毁事件创建侦听器?
【发布时间】:2018-01-05 09:36:58
【问题描述】:

我有如下代码:

@Component
public class LogoutListener implements ApplicationListener<SessionDestroyedEvent>
{
  @Override
  public void onApplicationEvent(SessionDestroyedEvent event)
  {
    System.out.println("Application event happened");
    for (SecurityContext securityContext : event.getSecurityContexts())
    {
        System.out.println("session has ended");   
    }
  }
}

由于我使用的是 Spring Boot 应用程序。我不能使用 web.xml。那么我该如何配置监听器。 此侦听器正在寻找会话被破坏的事件。

【问题讨论】:

    标签: spring-session


    【解决方案1】:

    我认为here 的答案可能会有所帮助。在其中您会发现,对于没有 web.xml 的应用程序,您必须查看 ServletContext.html#addListener

    【讨论】:

    • 帮助傻瓜,是的。请写下您的问题,以便在您所指的链接失效时它们甚至会有价值。
    • 同意。您必须在问题本身中包含信息。链接过期后,您的问题将毫无用处。
    • @Clijsters, L. Guthardt:当你说 questions 时,你的意思是 answer 吗?所以你说的是我应该包括来自引用链接的全部信息,对吧?抱歉,您可能会注意到这是我的第一个贡献。
    • 是的,对不起。我的意思是答案。好的,您是否像创建帐户时建议的那样使用tour?有一些有用的文章,如How do I write a good answer?
    【解决方案2】:

    这是一个例子:

    public class SessionEventListener extends HttpSessionEventPublisher {
    
        public void sessionCreated(HttpSessionEvent event) {
            super.sessionCreated(event);
            event.getSession().setMaxInactiveInterval(60*3);
        }
    
        @Override
        public void sessionDestroyed(HttpSessionEvent event) {
            String name = null;
            SessionRegistry sessionRegistry = getSessionRegistry(event);
            SessionInformation sessionInfo = (sessionRegistry != null ? sessionRegistry
                .getSessionInformation(event.getSession().getId()) : null);
            UserDetails ud = null;
            if (sessionInfo != null) {
                ud = (UserDetails) sessionInfo.getPrincipal();}
            if (ud != null) {
                name = ud.getUsername();
                // YOUR METHOD IS CALLED HERE 
                getMyService(event).myMethod(name);
            }
            super.sessionDestroyed(event);
        }
    
        public YourBean4Service getMyService(HttpSessionEvent event) {
            HttpSession session = event.getSession();
            ApplicationContext ctx =
                WebApplicationContextUtils.
                        getWebApplicationContext(session.getServletContext());
            return (YourBean4Service) ctx.getBean("yourBean4Service");
        }
    
        public SessionRegistry getSessionRegistry(HttpSessionEvent event) {
            HttpSession session = event.getSession();
            ApplicationContext ctx =
                WebApplicationContextUtils.
                        getWebApplicationContext(session.getServletContext());
            return (SessionRegistry) ctx.getBean("sessionRegistry");
        }
    }
    

    而我的相关话题是here

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 2017-06-13
      相关资源
      最近更新 更多