복붙노트

[SPRING] Spring에서 Session Expiry 이전에 커스텀 이벤트 수행

SPRING

Spring에서 Session Expiry 이전에 커스텀 이벤트 수행

나는 스프링 프레임 워크에서 초보자이다.

내 경우 세션은 다음과 같이 만료 될 수 있습니다. -> 성공 로그 아웃 (명시 적 로그 아웃)

-> 세션 시간 초과 (암시 적 로그 아웃)

일부 사용자가 로그인 할 때마다 데이터베이스에 DML (레코드 삽입)을 수행하고 사용자 세션 시간 초과 (암시 적 로그 아웃)가있을 때마다 데이터베이스에서 DML (레코드 삭제)을 수행하려고합니다.

제 질문은 세션이 끝나기 전에 우리에게 말해주는 어떤 방법이든 봄에 있습니다. 따라서 세션 만료 전에 맞춤 이벤트를 수행 할 수 있습니다.

미리 감사드립니다.

해결법

  1. ==============================

    1.네, SessionDestroyedEvent로 할 수 있습니다.

    네, 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>
    

    이 이벤트는 정기적 인 로그 아웃과 세션 시간 초과에 대해 시작됩니다.

  2. ==============================

    2.나는 @ 코도 답변과 비슷한 방식으로 내 문제를 해결했다.

    나는 @ 코도 답변과 비슷한 방식으로 내 문제를 해결했다.

    @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
         }  
    }   
    }
    
  3. from https://stackoverflow.com/questions/27753111/perform-custom-event-before-session-expiry-in-spring by cc-by-sa and MIT license