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

Spa*_*jjm 5 java session events spring timeout

我想在用户从会话超时中注销时执行自定义事件。在我的 application.properties 指定的时间长度后,用户成功注销:

server.servlet.session.timeout=10
server.servlet.session.cookie.max-age=10
Run Code Online (Sandbox Code Playgroud)

我发现了一些涉及 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是 SessionDestroyedEvent 未与会话超时同时触发,在我的测试中,它在会话过期后最多 5 分钟触发。

我也尝试过在 HttpSessionListener 中使用 sessionDestroyed 但结果相似。

是否有一个事件会在会话到期时触发,或者有什么方法可以实现这一点?

use*_*339 2

sessionDestroyed()当 Web 容器使会话过期时,将调用该方法。在 Tomcat 中,会话过期每分钟都会发生,我认为其他 servlet 容器也是如此。因此,即使在会话超时之后,在下次检测到过期之前也可能会出现延迟。

会话管理由 servlet 容器完成,您的应用程序将从它获取通知。并且无法在会话到期的确切时间得到通知。