我设置了以下属性
server.servlet.session.timeout=30s
在我的应用程序属性中,但未触发 session 超时。 但设置后
server.servlet.session.cookie.max-age=30s
session 超时已触发,但以下用于更新注销时间的代码未触发。
@Component
public class LogoutListener implements ApplicationListener<SessionDestroyedEvent> {
@Override
public void onApplicationEvent(SessionDestroyedEvent event)
{
List<SecurityContext> lstSecurityContext = event.getSecurityContexts();
UserDetails ud;
for (SecurityContext securityContext : lstSecurityContext)
{
ud = (UserDetails) securityContext.getAuthentication().getPrincipal();
us.findAllUsersByEmail(ud.getUsername()).get(0).setLastLogout(LocalDateTime.now());
System.out.println("lastloginspec : " + ud.getUsername() + " : 00 : " + LocalDateTime.now());
}
}
}
@Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
}
谁能帮帮我吗?
最佳答案
我通过以下方式实现了 session 监听器。
创建自定义 http session 监听器。
@Component public class CustomHttpSessionListener implements HttpSessionListener{ private static final Logger LOG= LoggerFactory.getLogger(Test.class); @Override public void sessionCreated(HttpSessionEvent se) { LOG.info("New session is created."); UserPrincipal principal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } @Override public void sessionDestroyed(HttpSessionEvent se) { LOG.info("Session destroyed."); UserPrincipal principal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); }}
调用新的ServletListenerRegistrationBean并向其中添加CustomHttpListener并将其注释为@Bean。
@Autowired private CustomHttpSessionListener customHttpSessionListener; @Bean public ServletListenerRegistrationBean<CustomSessionListner>sessionListenerWithMetrics() { ServletListenerRegistrationBean<CustomSessionListner> listenerRegBean = new ServletListenerRegistrationBean<>(); listenerRegBean.setListener(customHttpSessionListener); return listenerRegBean; }
向 application.properties 添加属性
server.servlet.session.timeout = 15m
关于spring - Spring Boot session 超时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63079913/