Spring Boot 使用session監聽器
阿新 • • 發佈:2018-11-24
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.