在 Spring 中会话到期之前执行自定义事件

Perform custom event before Session Expiry in 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>

常规注销和会话超时都会触发此事件。

我已经按照类似@Codo 的回答解决了我的问题

@Component
public class SessionCreatedListenerService implements ApplicationListener<ApplicationEvent> {

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
     }  
}   
}
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.LogoutSuccessEvent;
import org.springframework.stereotype.Component;

@Component 

public class LogoutSuccessListener implements ApplicationListener<LogoutSuccessEvent>{

    @Override
    public void onApplicationEvent(LogoutSuccessEvent evt) {
         String login = evt.getAuthentication().getName();
         System.out.println(login + " has just logged out");
    } 
}