Spring Boot 使用session監聽器

session存在服務端,session監聽器能夠用來跟蹤session的生命週期。spring-boot項目愈來愈流行,我就記錄下spring boot項目中使用session監聽器的過程,以便之後參考。java

spring boot使用監聽器很是方便,使用這2個註解就可自動加載註冊了:@WebListener和@ServletComponentScan web

爲了加深理解,使用在線百度翻譯了下:當使用嵌入式容器時,能夠經過使用@ServletComponentScan啓用@WebServlet、@WebFilter和@WebListener註釋的類的自動註冊。spring

關鍵在於:在啓動類上使用@ServletComponentScan,就能夠自動掃描使用@WebServlet、@WebFilter和@WebListener註解的類完成自動註冊。數據庫

1.編寫session監聽器類實現HttpSessionListener接口,並加上@WebListener註解,聲明此類是一個監聽器。session

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)註解的類,完成註冊。ide

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的生命週期了。spring-boot

注意:HttpServletRequest的getSession()方法,若是當前請求沒有對應的session會自動建立session。spa

 

使用getSession(false)就不會建立session,若是沒有當前請求對應的session就返回null.翻譯

相關文章
相關標籤/搜索