Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform custom event before Session Expiry in Spring

I am beginner in Spring framework.

In my case Session can be expire by following way
--> Success Log-out (Explicit Log-out )

--> Session Timeout (Implicit Log-out )

I have do DML(record insertion) in database whenever some user log in and I want to perform DML(record deletion) in database whenever user session timeout (Implicit Log-out).

My Question is that is there any way in Spring that tell us before the expiry of session. So I can do perform my custom event before session expiry.

Thanks in advance

like image 989
Yasir Shabbir Choudhary Avatar asked Jan 03 '15 08:01

Yasir Shabbir Choudhary


2 Answers

Yes, you can do that with 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
        }
    }

}

And in web.xml:

<listener>
    <listener-class>
        org.springframework.security.web.session.HttpSessionEventPublisher
    </listener-class>
</listener>

This event will be fired for both the regular logout as well as the session timeout.

like image 195
Codo Avatar answered Nov 19 '22 16:11

Codo


I have solved my problem by following way similar @Codo answer

@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
     }  
}   
}
like image 24
Yasir Shabbir Choudhary Avatar answered Nov 19 '22 17:11

Yasir Shabbir Choudhary