Spring 启动会话超时事件侦听器
Spring boot session timeout event listener
我想在用户因会话超时注销时执行自定义事件。用户在我指定的时间长度后成功注销 application.properties:
server.servlet.session.timeout=10
server.servlet.session.cookie.max-age=10
我发现了一些涉及 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
}
}
}
问题是 SessionDestroyedEvent 没有在会话超时的同时触发,在我的测试中它在会话过期后最多 5 分钟触发。
我也尝试过在 HttpSessionListener 中使用 sessionDestroyed,但结果相似。
是否有一个事件会在会话过期时触发,或者有什么方法可以实现吗?
Web 容器使会话过期时调用 sessionDestroyed()
方法。
在 Tomcat 中,会话过期每分钟都会发生,我认为其他 servlet 容器也是如此。
因此,即使在会话超时之后,也可能会延迟到下一次过期检测。
会话管理由 servlet 容器完成,您的应用程序从中获取通知。
并且无法在会话到期的确切时间得到通知。
我还处理了用户因会话超时注销时的事件。对我来说,这个解决方案很有帮助:
此外,我必须按照 中所述注册 HttpSessionEventPublisher,因为我没有 web.xml 用于注册侦听器。
我想在用户因会话超时注销时执行自定义事件。用户在我指定的时间长度后成功注销 application.properties:
server.servlet.session.timeout=10
server.servlet.session.cookie.max-age=10
我发现了一些涉及 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
}
}
}
问题是 SessionDestroyedEvent 没有在会话超时的同时触发,在我的测试中它在会话过期后最多 5 分钟触发。
我也尝试过在 HttpSessionListener 中使用 sessionDestroyed,但结果相似。
是否有一个事件会在会话过期时触发,或者有什么方法可以实现吗?
Web 容器使会话过期时调用 sessionDestroyed()
方法。
在 Tomcat 中,会话过期每分钟都会发生,我认为其他 servlet 容器也是如此。
因此,即使在会话超时之后,也可能会延迟到下一次过期检测。
会话管理由 servlet 容器完成,您的应用程序从中获取通知。 并且无法在会话到期的确切时间得到通知。
我还处理了用户因会话超时注销时的事件。对我来说,这个解决方案很有帮助:
此外,我必须按照 中所述注册 HttpSessionEventPublisher,因为我没有 web.xml 用于注册侦听器。