2015-01-03 3 views
7

저는 Spring 프레임 워크에서 초보자입니다. 방법
에 따라 만료 될 수 내 경우 세션에서Spring에서 Session Expiry 전에 커스텀 이벤트 수행하기

-> 성공 로그 아웃 (명시 로그 아웃)

-> 세션 제한 시간 (암시 적 로그 아웃) 내가 가지고있는

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

내 질문은 세션의 만료 전에 알려주는 방법이 있다는 것입니다. 그래서 세션 만료 전에 맞춤 이벤트를 수행 할 수 있습니다. 사전에

감사

+0

이 위험에 대답 @Codo 유사한 방법에 따라 내 문제를 해결했다? 사용자 세션이 활성화되었을 때 앱이 다운되면 어떻게 될까요? – SMA

+0

다음 단계는 무엇입니까? –

+0

정말 DB에 어떤 레코드를 저장하고 그 레코드가 얼마나 중요한지에 따라 달라집니다. – SMA

답변

14

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

이 이벤트는 정기적으로 로그 아웃뿐만 아니라 세션 제한 시간을 모두 해고 될 것입니다.

+0

당신이 할 수없는 것은 무엇입니까? 사용중인 특정 응용 프로그램 서버를 해킹하지 않는 한 사실 이전에 이벤트를 가져올 수 없으면 사실을 알리는 동안 또는 후에 이벤트를받습니다. –

+0

예 해결책을 얻었습니다 @ 코도 귀하의 대답은 도움이됩니다. –

+0

이 접근 방식을 사용하려면 'Spring Security'구성 요소가 내 종속성에 필요합니다. 등록해야 할 청취자를 본 후에 나는이 질문을했습니다. – yathirigan

4

난 당신이 통지를 그리워 어떤 경우 ..

@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 
    } 
} 
} 
+0

내 Spring Boot 응용 프로그램의 Session Destroy 이벤트 동안, 솔루션에서 언급 한 것처럼 HttpSessionDestroyedEvent 대신 applicationEvent가 SessionFactory 이벤트와 instanceof SessionDestroyedEvent 만 볼 수 있습니다. 그 차이점은 무엇입니까? – yathirigan

관련 문제