如何为spring会话破坏事件创建监听器?

问题描述 投票:0回答:2

我有一个代码如下:

@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 app.I不能使用web.xml。然后我该如何配置监听器。此侦听器正在查找会话已销毁的事件。

spring-session
2个回答
0
投票

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


0
投票

这是一个例子:

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

© www.soinside.com 2019 - 2024. All rights reserved.