@Bean
public HttpSessionListener httpSessionListener(TaggingServiceImpl taggingService) {
return new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
logger.info(se.getSession().getId() + " [SESSION CREATED]");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
SecurityContextImpl securityContext = (SecurityContextImpl) se.getSession().getAttribute(SPRING_SECURITY_CONTEXT);
Authentication authentication = securityContext.getAuthentication();
User user = (User) authentication.getPrincipal();
TaggingUser u = userDetailsService.queryByUsername(user.getUsername(), TaggingUser.Column.id);
taggingService.clearUsingByUserId(u.getId());
logger.info(user.getUsername() + "[SESSION EXPIRED]");
}
};
}
@Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisherServletListenerRegistrationBean() {
System.out.println("开始监听session");
return new ServletListenerRegistrationBean<>(new HttpSessionEventPublisher());
}
```
```java
package org.tagging.component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
public class HttpSessionListener implements javax.servlet.http.HttpSessionListener {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void sessionCreated(HttpSessionEvent se) {
logger.info("Session is created!");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
logger.info("Session id destroyed!");
}
}