JavaWeb-監聽器

一.監聽器web

  1.JavaWeb中有三大組件:Servlet,Listener,Filtersession

  2.最開始接觸監聽器時是在JavaSE的awt,如今講的是JavaWeb中的應用spa

  3.它是一個接口,須要咱們來實現code

  4.在Web中是須要註冊的,在web.xml中,不過註冊比Servlet簡單多了xml

  5.監聽器能夠監聽對象是否發生某個事件,並調用特定的方法;即監聽器也是處理器;對象

二.觀察者blog

  1.事件源:參與事件的對象接口

  2.事件:好比點擊事件生命週期

  3.監聽器:監聽事件源是否發生事件事件

三.JavaWeb監聽器

  1.Web監聽器監聽的是三大域:ServletContext,HttpSession,ServletRequest

  2.三大域中各個域都有兩個特有的監聽器:生命週期監聽(生死監聽)和屬性監聽,他們的命週期監聽和屬性監聽所表達的意思相同

  3.ServletContext

    >生命週期監聽:ServletContextListener

      方法:contextInitialized(ServletContextEvent sce),ServletContext建立後立刻調用,參數爲事件對象,能夠獲取到事件源

         contextDestroyed(ServletContextEvent sce),ServletContext銷燬前立刻調用,參數爲事件對象,能夠獲取到事件源

    >屬性監聽:ServletContextAttributeListener

      方法:attributeAdded(ServletContextAttributeEvent event),添加屬性時調用

         attributeRemoved(ServletContextAttributeEvent event),移除屬性時調用

         attributeReplaced(ServletContextAttributeEvent event),修改屬性時調用,注意的參數事件對象的getValue()獲取的時老值,而不是新值

  4.HttpSession

    >生命週期監聽:HttpSessionListener

      方法:sessionCreated(HttpSessionEvent se),HttpSession建立後立刻調用,參數爲事件對象,能夠獲取到事件源

         sessionDestroyed(HttpSessionEvent se),HttpSession銷燬前立刻調用,參數爲事件對象,能夠獲取到事件源

    >屬性監聽:HttpSessionAttributeListener

      方法:attributeAdded(HttpSessionBindingEvent event),添加屬性時調用

         attributeRemoved(HttpSessionBindingEvent event),移除屬性時調用

         attributeReplaced(HttpSessionBindingEvent event),修改屬性時調用,注意的參數事件對象的getValue()獲取的時老值,而不是新值

  5.ServletRequest

    >生命週期監聽:ServletRequestListener

      方法:requestInitialized(ServletRequestEvent sre),ServletRequest建立後立刻調用,參數爲事件對象,能夠獲取到事件源

         requestDestroyed(ServletRequestEvent sre),ServletRequest銷燬前立刻調用,參數爲事件對象,能夠獲取到事件源

    >屬性監聽:ServletRequestAttributeListener

      方法:attributeAdded(ServletRequestAttributeEvent srae),添加屬性時調用

         attributeRemoved(ServletRequestAttributeEvent srae),移除屬性時調用

         attributeReplaced(ServletRequestAttributeEvent srae),修改屬性時調用,注意的參數事件對象的getValue()獲取的時老值,而不是新值

 

四.感知監聽

  1.感知監聽並非監聽三大域,它監聽的是JavaBean對象,並且跟httpSession相關

  2.感知監聽不須要註冊

  3.感知監聽有兩個:

    >HttpSessionBindingListener(監聽bean有沒有被添加到session域或從sesion中移除)

      (1)咱們須要讓JavaBean類去實現該監聽器接口,就至關於bean本身監聽本身跟session的狀態關係

      (2)有以下兩個方法:

          * valueBound(HttpSessionBindingEvent event),當bean對象被添加到session域中,調用該方法

          * valueUnbound(HttpSessionBindingEvent event),當bean對象被移除到session域中,調用該方法

    >HttpSessionActivationListener(監聽bean有沒有隨session鈍化或活化)

      (1)須要讓JavaBean類去實現該監聽器接口

      (2)有以下兩個方法:

          *  sessionWillPassivate(HttpSessionEvent se),當該bean對象隨session鈍化後當即調用的方法

          * sessionDidActivate(HttpSessionEvent se),當該bean對象隨session活化後當即調用的方法

      (3)注意的是:添加在session域中的對象必須是實現了序列化接口Serializable,否則沒法鈍化到硬盤上

.監聽器註冊格式

   1.到web.xml註冊,如圖:

      

相關文章
相關標籤/搜索