I am currently planning an application that requires a function to run whenever a session is created and expires. I'm planning on using something like redis but I am open to other ideas. What i am looking for is a n annotation such as @whenexpires and @whencreated. I know that most of the annotations for sessions are at the class, and notthemethod Thanks in regards.
As of Servlet specification 2.3, Java Servlet containers like Apache Tomcat provide the HttpSessionListener interface in order to execute custom logic in the event of created or destroyed sessions. Basic usage:
package com.example;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent event) {
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
}
}
Add MySessionListener
to your web.xml
or - in case of Spring - declare a Spring bean for it that is detected by Spring. However, Spring is not required as HttpSessionListener
is part of the Java Servlet spec.
If you go for Spring Session with Redis, you can continue using your HttpSessionListener
by adding it to the Spring configuration as described in the official docs.
@EnableRedisHttpSession
public class Config {
@Bean
public MySessionListener mySessionListener() {
return new MySessionListener();
}
// more Redis configuration comes here...
}
Moreover, Spring Session comes with support for the "Spring-native" way of event subscription and publishing: ApplicationEvent. Depending on the session persistence approach, there are currently up to three events that can be catched by your application: SessionExpiredEvent
, SessionCreatedEvent
, SessionDestroyedEvent
.
Implement an EventListener
in order to subscribe to Spring Session events, for example:
package com.example;
import org.springframework.context.event.EventListener;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDestroyedEvent;
import org.springframework.session.events.SessionExpiredEvent;
import org.springframework.stereotype.Component;
@Component
public class MySessionEventListener {
@EventListener
public void sessionDestroyed(SessionDestroyedEvent event) {
}
@EventListener
public void sessionCreated(SessionCreatedEvent event) {
}
@EventListener
public void sessionExired(SessionExpiredEvent event) {
}
}