简体   繁体   English

Spring启动会话超时事件监听器

[英]Spring boot session timeout event listener

I want to perform a custom event when a user is logged out from a session timeout.我想在用户从会话超时中注销时执行自定义事件。 The user is successfully logged out after exactly the length of time specified by my application.properties:用户在我的 application.properties 指定的时间长度后成功注销:

server.servlet.session.timeout=10
server.servlet.session.cookie.max-age=10

I have found a few similar solutions which involve a SessionDestroyedEvent, for example:我发现了一些涉及 SessionDestroyedEvent 的类似解决方案,例如:

@Slf4j
@Component
public class SessionExpiredListener implements ApplicationListener<SessionDestroyedEvent> {

    @Override
    public void onApplicationEvent(SessionDestroyedEvent event) {
        for (SecurityContext securityContext : event.getSecurityContexts()) {
            Authentication authentication = securityContext.getAuthentication();
            UserPrincipal user = (UserPrincipal) authentication.getPrincipal(); // UserPrincipal is my custom Principal class
            log.debug("Session expired!" + user.getUsername());
            // do custom event handling
        }
    }
}

The problem is the SessionDestroyedEvent is not triggered at the same time as the session timeout, in my tests it has triggered up to 5 minutes after the session has expired.问题是 SessionDestroyedEvent 未与会话超时同时触发,在我的测试中,它在会话过期后最多 5 分钟触发。

I have also tried using sessionDestroyed in HttpSessionListener but with similar results.我也尝试过在 HttpSessionListener 中使用 sessionDestroyed 但结果相似。

Is there an event that will trigger exactly when the session expires, or is there some way to achieve this?是否有一个事件会在会话到期时触发,或者有什么方法可以实现这一点?

The sessionDestroyed() method is called when the web container expires the session. sessionDestroyed()方法在 Web 容器使会话过期时被调用。 In Tomcat, session expirations happens every minute, and I think it is the case with other servlet containers.在 Tomcat 中,会话过期每分钟都会发生一次,我认为其他 servlet 容器也是如此。 So, even after the session times out there could be a delay until the next detection of expirations.因此,即使在会话超时之后,在下一次检测到到期之前也可能会有延迟。

Session management is done by servlet container, and your application is getting notification from it.会话管理由 servlet 容器完成,您的应用程序正在从中获取通知。 And there is no way to be notified at the exact time of session expiration.并且无法在会话到期的确切时间收到通知。

I also had handle the event when the user is logged out by session timeout.当用户因会话超时而注销时,我也处理了该事件。 For me, this solution was helpfull: https://stackoverflow.com/a/18128496/4074871对我来说,这个解决方案很有帮助: https : //stackoverflow.com/a/18128496/4074871

Additionally I had to register the HttpSessionEventPublisher as mentioned in https://stackoverflow.com/a/24957247/4074871 because I had no web.xml for listener registration.此外,我必须注册https://stackoverflow.com/a/24957247/4074871 中提到的 HttpSessionEventPublisher,因为我没有用于侦听器注册的 web.xml。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM