How can I get a list of all sessions in Spring?

后端 未结 1 809
故里飘歌
故里飘歌 2021-01-14 12:46

I\'m developing a web app using Spring Boot 2 and Gradle. I currently implemented a custom remember me mechanism (WITHOUT Spring Security), and I added also a serie

1条回答
  •  有刺的猬
    2021-01-14 12:55

    You have to create a custom HttpSession holder object that will hold active sessions that you can iterate and invalidate based on your conditions.

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpSessionEvent;
    import javax.servlet.http.HttpSessionListener;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    
    @Configuration
    public class HttpSessionConfig {
    
        private static final Map sessions = new HashMap<>();
    
        public List getActiveSessions() {
            return new ArrayList<>(sessions.values());
        }
    
        @Bean
        public HttpSessionListener httpSessionListener() {
            return new HttpSessionListener() {
                @Override
                public void sessionCreated(HttpSessionEvent hse) {
                    sessions.put(hse.getSession().getId(), hse.getSession());
                }
    
                @Override
                public void sessionDestroyed(HttpSessionEvent hse) {
                    sessions.remove(hse.getSession().getId());
                }
            };
        }
    } 
    

    0 讨论(0)
提交回复
热议问题