在spring会话到期之前执行自定义事件
问题内容:
我是Spring框架的初学者。
在我的情况下,会话可以通过以下方式过期
->成功注销(显式注销)
->会话超时(隐式注销)
每当某些用户登录时,我都会在数据库中执行DML(记录插入),并且每当用户会话超时(隐式注销)时,我都希望在数据库中执行DML(记录删除)。
我的问题是,Spring在会议期满前有什么办法告诉我们。因此,我可以在会话到期前执行自定义事件。
提前致谢
问题答案:
是的,您可以使用SessionDestroyedEvent做到这一点。
@Component
public class SessionEndedListener implements ApplicationListener<SessionDestroyedEvent> {
@Override
public void onApplicationEvent(SessionDestroyedEvent event)
{
for (SecurityContext securityContext : event.getSecurityContexts())
{
Authentication authentication = securityContext.getAuthentication();
YourPrincipalClass user = (YourPrincipalClass) authentication.getPrincipal();
// do something
}
}
}
并在web.xml中:
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
常规注销和会话超时都会触发此事件。