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

我是Spring框架的初学者。

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

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

无论何时某个用户登录,我都在数据库中进行DML(记录插入),并且每当用户会话超时(隐式注销)时我想在数据库中执行DML(记录删除)。

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

提前致谢

是的,你可以使用SessionDestroyedEvent来做到这一点 。

@Component public class SessionEndedListener implements ApplicationListener { @Override public void onApplicationEvent(SessionDestroyedEvent event) { for (SecurityContext securityContext : event.getSecurityContexts()) { Authentication authentication = securityContext.getAuthentication(); YourPrincipalClass user = (YourPrincipalClass) authentication.getPrincipal(); // do something } } } 

在web.xml中:

   org.springframework.security.web.session.HttpSessionEventPublisher   

将针对常规注销以及会话超时触发此事件。

我通过类似@Codo回答的方式解决了我的问题

 @Component public class SessionCreatedListenerService implements ApplicationListener { private static final Logger logger = LoggerFactory .getLogger(SessionCreatedListenerService.class); @Autowired HttpSession httpSession; @Override public void onApplicationEvent(ApplicationEvent applicationEvent) { if(applicationEvent instanceof HttpSessionCreatedEvent){ //If event is a session created event }else if(applicationEvent instanceof HttpSessionDestroyedEvent){ //If event is a session destroy event // handler.expireCart(); logger.debug(""+(Long)httpSession.getAttribute("userId")); logger.debug(" Session is destory :" ); //log data }else if(applicationEvent instanceof AuthenticationSuccessEvent){ //If event is a session destroy event logger.debug(" athentication is success :" ); //log data }else{ /*logger.debug(" unknown event occur : " Source: " + ); //log data } } }