SpringBoot 2,HttpSessionListener注冊方法
項目中需要控制並發登錄,搜索了很多地方,都是講需要配置兩個地方,大概代碼如下:
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
// 配置spring security
http.sessionManagement()
.maximumSessions(1) // 控制並發的數量
.maxSessionsPreventsLogin(true) // 如果並發登錄,不允許后面的登錄,必須等到前一個登錄退出來
.sessionRegistry(this.sessionRegistry);
問題解析
首先,按照上面配置,是不可用的,因為session的創建和銷毀都沒有被監聽,因此,很多文章會告訴我們要配置一個HttpSessionListener
,於是,我搜到很多個寫法
寫法1
@WebListener
public class MyListener implements HttpSessionListener {
...
}
這種寫法有點類似寫web.xml,同時還需要在程序入口加上注解@ServletComponentScan
,經過測試,MyListener
里面的方法不會被調用
寫法2
@Bean
public HttpSessionListener httpSessionListener() {
return new HttpSessionEventPublisher();
}
stackoverflow上基本上都是這種寫法,甚至spring官方文檔也語焉不詳的寫了這么一段,測試這么做是不行的
正確寫法
@Bean
public ServletListenerRegistrationBean<HttpSessionListener> sessionListenerWithMetrics() {
ServletListenerRegistrationBean<HttpSessionListener> listenerRegBean = new ServletListenerRegistrationBean<>();
listenerRegBean.setListener(new HttpSessionEventPublisher());
return listenerRegBean;
}
只有這么寫是可以的,具體參考這里