JSP筆記——9.Listener介紹

Listener可以用來監聽不同的web事件。使用Listener,首先要有Listener實現類,然後要在web.xml中配置Listener(或者通過註解)。常用的Web事件監聽器接口如下:

  • ServletContextListener:監聽web應用的啓動和關閉

  • ServletContextListener:監聽ServletContext範圍(application)內容屬性的改變

  • ServletRequestListener:監聽用戶請求

  • ServletRequestAttributeListener:監聽ServletRequest範圍內的屬性變化

  • HttpSessionListener:用於監聽session的開始和結束

  • HttpsessionAttributeListener:監聽session內屬性的改變

ServletContextListener接口中的方法,contestInitialized()跟contextDestroyed()方法分別在應用啓動、關閉的時候被觸發。


配置Listener

配置Listener十分簡單,只需要簡單滴指定Listener實現類就行,不能配置初始化參數。只需在xml中用listener子元素的listener-class配置listener的實現類即可。如果配置了一個實現了ServletContextListener的監聽類,那麼當web應用被啓動的時候,該listener的contextInitialized方法會被觸發。


使用ServletContextAttributeListener

這個接口可以用於監聽application範圍內的屬性的變化。實現該接口需要實現如下三個方法:

attributeAdded(ServletContextAttributeEvent event):存入屬性觸發

attributeRemoved(ServletContentAttributeEvent event):刪除屬性觸發

attributeReplaced(ServletContentAttributeEvent event):替換屬性觸發


使用ServletRequestListener和ServletRequestAttributeListener

ServletRequestListener用於監聽用戶請求到達。實現該接口需要requestinitialized(servletRequestEvent sre)和requestDestroyed(ServletRequestEvent sre)這兩個接口。第一個會在用戶請求到達、被初始化時觸發,第二個會在用戶請求結束、被銷燬的時候觸發。

ServletRequestAttributeListener用於監聽request範圍內的變化,需要實現attributeAdded()、attributeRemoved()、attributeReplaced()三個方法

一個監聽類如果實現了多個接口,就能即監聽application範圍變化,又能監聽request範圍變化。

HttpSessionListener和HttpSessionAttributeListener

HttpSessionListener用於監聽session的創建跟銷燬,需要實現sessionCreated(HttpSessionEvent se):方法和sessionDestroyed(HttpSessionEvent se)。

類似地,HttpSessionAttributeListener則用於監聽HttpSesson範圍的變化,需要實現attributeAdded、attributeRemoved、attributeReplaced三個方法。實現HttpSessonListener接口的監聽器可以監聽每個用戶回話的開始和斷開,因此可以利用該接口來監聽系統用戶的在線用戶。此外通過分析request可以更詳細地得到用戶在線的各種信息

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章