來源於 https://www.cnblogs.com/liuyong1993/p/10012808.html
session存在服務端,session監聽器可以用來跟蹤session的生命周期。spring-boot項目越來越流行,我就記錄下spring boot項目中使用session監聽器的過程,以便以后參考。
spring boot使用監聽器非常方便,使用這2個注解就可自動加載注冊了:@WebListener和@ServletComponentScan

為了加深理解,使用在線百度翻譯了下:當使用嵌入式容器時,可以通過使用@ServletComponentScan啟用@WebServlet、@WebFilter和@WebListener注釋的類的自動注冊。
關鍵在於:在啟動類上使用@ServletComponentScan,就可以自動掃描使用@WebServlet、@WebFilter和@WebListener注解的類完成自動注冊。
1.編寫session監聽器類實現HttpSessionListener接口,並加上@WebListener注解,聲明此類是一個監聽器。
package com.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* session監聽器
* @author Administrator
*/
@WebListener
public class SessionListener implements HttpSessionListener{
private int onlineCount = 0;//記錄session的數量
/**
* session創建后執行
*/
@Override
public void sessionCreated(HttpSessionEvent se) {
onlineCount++;
System.out.println("【HttpSessionListener監聽器】 sessionCreated, onlineCount:" + onlineCount);
se.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
}
/**
* session失效后執行
*/
@Override
public void sessionDestroyed(HttpSessionEvent se) {
if (onlineCount > 0) {
onlineCount--;
}
System.out.println("【HttpSessionListener監聽器】 sessionDestroyed, onlineCount:" + onlineCount);
se.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
}
}
2.啟動類上使用@ServletComponentScan,自動掃描帶有(@WebServlet, @WebFilter, and @WebListener)注解的類,完成注冊。
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})//無數據庫運行
@ServletComponentScan //scans from the package of the annotated class (@WebServlet, @WebFilter, and @WebListener)
public class WebApp{
public static void main(String[] args) {
System.out.println(" springApplication run !");
SpringApplication.run(WebApp.class,args);
}
}
只用簡單的2個注解就完成了session監聽器的注冊。這樣就能監聽到容器session的生命周期了。
注意:HttpServletRequest的getSession()方法,如果當前請求沒有對應的session會自動創建session。

使用getSession(false)就不會創建session,如果沒有當前請求對應的session就返回null.


