We recently started using spring-session in our project. This is a legacy application and we have some HttpSessionListener. So when the session is expired or user invalidates the session sessionDestroyed(HttpSessionEvent se)
method is called. You can get hold of the HttpSession
that is about to be destroyed by calling getSession()
method on HttpSessionEvent
Spring sessions also has something similar. The Redis Session Repository implementation will fire org.springframework.session.events.SessionDestroyedEvent
event and you can add a ApplicationListener to it to do some processing.
But this does not fullfill my need.
The problem that i am having is, it cannot be used to migrate our existing HttpSessionListener to use these even because of 2 main reason
The event fired by Spring Session only gives the session id that is about to be destroyed. It does not give a copy of the entire session objects. So if my existing HttpSessionListener has some logic to use some attributes for some processing, i cannot do it now.
There is no event when the session is created. We have HttpSessionListener which does some work when sessions are created.
So what all options do i have to get our functionality that we had with HttpSessionListener working in spring session?
Spring Session has support for HttpSessionListener from spring session 1.1.
You will have to configure SessionEventHttpSessionListenerAdapter as a bean in the HttpSessionConfig file as follows:
@Bean
public SessionEventHttpSessionListenerAdapter session() {
List<HttpSessionListener> listeners = new ArrayList<HttpSessionListener>();
listeners.add(new MyListener());
return new SessionEventHttpSessionListenerAdapter(listeners);
}
As you see above, I have registered my custom HttpSessionListener called MyListener. In this you can configure the session created and destroyed events as required.
public class MyListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("CREATED--------");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("DELETED--------");
}
}
Let me know if this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With