一、今日內容
1. Listener概述
2. ServletContextListener監聽器接口
二、Listener學習
1. Listener概述
概念:web的三大組件之一。
* 事件監聽機制
* 事件 :一件事情
* 事件源 :事件發生的地方
* 監聽器 :一個對象
* 註冊監聽:將事件、事件源、監聽器綁定在一起。 當事件源上發生某個事件後,執行監聽器代碼
2. ServletContextListener監聽器接口
ServletContextListener:是一個接口。監聽ServletContext對象的創建和銷燬
* 方法:
* void contextDestroyed(ServletContextEvent sce) :ServletContext對象被銷燬之前會調用該方法。服務器正常關閉時會銷燬對象,自動調用該方法。
* void contextInitialized(ServletContextEvent sce) :ServletContext對象創建後會調用該方法。服務器啓動後會創建對象,自動調用該方法。
* 步驟:
1. 定義一個類,實現ServletContextListener接口
2. 複寫方法
3. 配置
1. web.xml
<listener>
<listener-class>cn.itcast.web.listener.ContextLoaderListener</listener-class>
</listener>
* 指定初始化參數
* 在項目中把資源路徑寫死不太好,我們將資源路徑配置到web.xml文件中,到時候只用改web.xml文件中的路徑就可以了
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
2. 註解:
* @WebListener 沒有括號,就是這,不用指定參數
*作用:在服務器啓動時將一些資源文件加載進內存。服務器關閉時,釋放內存。