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

时间:2015-01-03 08:39:42

标签: java spring hibernate session spring-mvc

我是Spring框架的初学者。

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

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

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

我的问题是春天是否有任何方式在会话到期之前告诉我们。 所以我可以在会话到期之前执行我的自定义事件。

提前致谢

3 个答案:

答案 0 :(得分:16)

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

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

答案 1 :(得分:4)

我通过类似@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
     }  
}   
}

答案 2 :(得分:0)

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");
    } 
}