java常用的Listener分類

來源:互聯網
上載者:User

Listener是Servlet的監聽器,它可以監聽用戶端的請求、服務端的操作等。(通過監聽器,可以自動激發一些操作,比如監聽線上的使用者的數量。當增加一個HttpSession時,就激發 sessionCreated(HttpSessionEvent se)方法,這樣就可以給線上人數加1。)

Servlet 監聽器用於監聽一些重要事件的發生,監聽器對象在事情發生前、發生後可以做一些必要的處理。

目前 Servlet2.4 和 JSP2.0 常用的有7 個監聽器介面,分為3 類:

1. Servlet上下文進行監聽(Application級):
用於監聽 ServletContext 對象的建立和刪除以及屬性的添加、刪除和修改等操作,該監聽器需要用到如下兩個介面類:
(1) ServletContextAttributeListener:監聽對 ServletContext 屬性的操作,比如增加、刪除、修改
      attributeAdded(ServletContextAttributeEvent e)             添加屬性時調用    
      attributeReplaced(ServletContextAttributeEvent e)        修改屬性時調用    
      attributeRemoved(ServletContextAttributeEvent e)        刪除屬性時調用

(2) ServletContextListener:監聽對 ServletContext  對象的建立和刪除
      contextInitialized(ServletContextEvent sce)          初始化時調用    
      contextDestroyed(ServletContextEvent sce)        銷毀時調用,即當伺服器重新載入時調用

2. 監聽HTTP會話(Session級):
用 於監聽 HTTP 會話活動情況和 HTTP 會話中的屬性設定情況,也可以監聽 HTTP 會話的 active 和 passivate 情況等,該監聽器需要用到如下多個介面類:
(1) HttpSessionListener:監聽 HttpSession 的操作
      sessionCreate(HttpSessionEvent se)         初始化時調用;
      sessionDestroyed(httpSessionEvent se)    銷毀時調用,即當使用者登出時調用

(2) HttpSessionActivationListener:用於監聽 HTTP 會話的 active 和 passivate 情況

(3) HttpSessionAttributeListener:監聽 HttpSession 中的屬性操作
      attributeAdded(HttpSessionBindingEvent se)         添加屬性時調用
      attributeRemoved(HttpSessionBindingEvent se)    刪除屬性時調用
      attributeReplaced(HttpSessionBindingEvent se)    修改屬性時調用

3. 對用戶端請求進行監聽(Requst級):
用於對用戶端的請求進行 監聽是在 Servlet2.4 規範中新添加的一項新技術,使用的介面如下:
(1) ServletRequestListener 介面類
       requestDestroyed(ServletRequestEvent e)       對銷毀用戶端進行監聽,即當執行 request.removeAttribute("xxx") 時調用
       requestInitialized(ServletRequestEvent e)         對實現用戶端的請求進行監聽

(2) ServletRequestAttributeListener 介面類
       attributeAdded(ServletRequestAttributeEvent e)         對屬性添加進行監聽
       attributeRemoved(ServletRequestAttributeEvent e)    對屬性刪除進行監聽
       attributeReplaced(ServletRequestAttributeEvent e)    對屬性替換進行監聽

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.