【问题标题】:HttpSessionListener doesn't workHttpSessionListener 不起作用
【发布时间】:2015-12-20 19:03:09
【问题描述】:

我已经实现了 HttpSessionListiner 但它不起作用。 使用调试器检查它 - 进入 servlet 后创建新会话,登录后 JSESSION_ID 更改,但 session.getCreateTime() 保持不变(会话保持不变?)。 使用注解,Spring Security。也许我错过了 Spring Security 中的一些配置?

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;

@WebListener
public class SessionListener implements HttpSessionListener {

    private static int totalActiveSessions;
    private static final Logger log = Logger.getLogger(SessionListener.class);  

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        totalActiveSessions++;
        log.warn("sessionCreated - add one session into counter");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        totalActiveSessions--;
        log.debug("sessionDestroyed - deleted one session from counter");
    }
}

【问题讨论】:

  • 你在项目中使用spring-security吗?
  • @NallaSrinivas 是的,但是我尝试在其他项目中实现这个监听器,它不使用 Spring Security,它也不起作用。
  • 扩展 org.springframework.security.web.session。 ttpSessionEventPublisher 如果您使用的是 spring security 并在 web.xml 中指定此侦听器。如果你没有使用 spring security 然后检查 servlet api 版本,对你来说应该是 3.0
  • @NallaSrinivas 尝试扩展 HttpSessionEventPublisher,没有任何改变。我正在使用注释和 SpringBoot。 Servlet-api 3.1.0
  • 您在 web.xml 中指定了 ttpSessionEventPublisher 吗?还要检查 web.xml 中的 spring 安全过滤器。如果您使用的是 spring security 那么 SessionListener 应该从 ttpSessionEventPublisher 扩展并覆盖两个方法。

标签: java spring spring-mvc servlets spring-boot


【解决方案1】:

虽然不是发帖者的具体问题,但另一个问题是会话实际上并没有被创建,这意味着你的听众没有被触发。如果使用 Spring Security,默认的会话创建策略是 SessionCreationPolicy.IF_REQUIRED。

您可以根据需要在网络安全 Java 配置中更改此设置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
    }
}

来源:https://www.baeldung.com/spring-security-session

【讨论】:

    【解决方案2】:
    @Bean
    public ServletListenerRegistrationBean<HttpSessionListener> sessionListener() {
        return new ServletListenerRegistrationBean<HttpSessionListener>(new sessionListener());
    }
    

    这个 bean 注册了我的监听器。我还没有找到其他解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-11
      • 2016-02-02
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多