Java HttpSessionListener不';行不通

Java HttpSessionListener不';行不通,java,spring,spring-mvc,servlets,spring-boot,Java,Spring,Spring Mvc,Servlets,Spring Boot,我已经实现了HttpSessionListiner,但它不起作用。 与Debugger一起检查-新会话在进入servlet后创建,JSESSION_ID在登录后更改,但session.getCreateTime()保持不变(会话保持不变?)。 使用注释,Spring安全性。也许我错过了春季安全的一些配置 import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import j

我已经实现了HttpSessionListiner,但它不起作用。 与Debugger一起检查-新会话在进入servlet后创建,JSESSION_ID在登录后更改,但session.getCreateTime()保持不变(会话保持不变?)。 使用注释,Spring安全性。也许我错过了春季安全的一些配置

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");
    }
}
@Bean
公共ServletListenerRegistrationBean会话Listener(){
返回新的ServletListenerRegistrationBean(newSessionListener());
}

这个豆子注册了我的听众。我还没有找到另一个解决方案。

虽然不是海报的具体问题,但另一个问题是会话实际上没有被创建,这意味着你的听众没有被触发。如果使用Spring安全性,默认会话创建策略为SessionCreationPolicy.If_REQUIRED

您可以根据需要在web security java配置中更改此设置:

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

来源:

您的项目中是否使用了spring安全性?@NallaSrinivas是的,但我尝试在其他项目中实现此侦听器,它不使用spring安全性,也不起作用。extend org.springframework.security.web.session。ttpSessionEventPublisher,如果您使用的是spring安全性,请在web.xml中指定此侦听器。如果您没有使用SpringSecurity,那么请检查ServletAPI版本,它应该是3。0@NallaSrinivas试图扩展HttpSessionEventPublisher,未发生任何更改。我正在使用注释和SpringBoot。Servlet api 3.1.0是否在web.xml中指定了ttpSessionEventPublisher?。还要检查web.xml中的spring安全过滤器。如果您使用的是spring安全性,那么SessionListener应该从ttpSessionEventPublisher扩展,并重写两个方法。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
    }
}