在Spring中的Session Expiry之前执行自定义事件

Yas*_*ary 13 java session spring hibernate spring-mvc

我是Spring框架的初学者.

在我的情况下,会话可以通过以下方式到期
- >成功注销(显式注销)

- >会话超时(隐式注销)

一旦用户登录,我就在数据库中进行DML(记录插入),并且每当用户会话超时(隐式注销)时我想在数据库中执行DML(记录删除).

我的问题是春天有没有办法在会议结束前告诉我们.所以我可以在会话到期之前执行我的自定义事件.

提前致谢

Cod*_*odo 17

是的,你可以使用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
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

在web.xml中:

<listener>
    <listener-class>
        org.springframework.security.web.session.HttpSessionEventPublisher
    </listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)

将针对常规注销和会话超时触发此事件.