Servlet之Listener監聽器

n672 9年前發布 | 17K 次閱讀 Servlet Java開發


Servlet2.5規范共有8中Listener接口,6種Event類型

ServletContextListener接口

[接口方法] contextInitialized()與 contextDestroyed()

[接收事件] ServletContextEvent

[觸發場景] 在Container加載Web應用程序時(例如啟動Container之后),會呼叫contextInitialized(),而當容器移除Web應用程序時,會呼叫contextDestroyed ()方法。


ServletContextAttributeListener

[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()

[接收事件] ServletContextAttributeEvent

[觸發場景] 若有對象加入為application(ServletContext)對象的屬性,則會呼叫attributeAdded(),同理在置換屬性與移除屬性時,會分別呼叫attributeReplaced()、attributeRemoved()。


HttpSessionListener

[接口方法] sessionCreated()與sessionDestroyed ()

[接收事件] HttpSessionEvent

[觸發場景] 在session (HttpSession)對象建立或被消滅時,會分別呼叫這兩個方法。


HttpSessionAttributeListener

[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()

[接收事件] HttpSessionBindingEvent

[觸發場景] 若有對象加入為session(HttpSession)對象的屬性,則會呼叫attributeAdded(),同理在置換屬性與移除屬性時,會分別呼叫attributeReplaced()、 attributeRemoved()。


HttpSessionActivationListener

[接口方法] sessionDidActivate()與 sessionWillPassivate()

[接收事件] HttpSessionEvent

[觸發場景]Activate與Passivate是用于置換對象的動作,當session對象為了資源利用或負載平衡等原因而必須暫時儲存至硬盤或其它儲存器時(透過對象序列化),所作的動作稱之為Passivate,而硬盤或儲存器上的session對象重新加載JVM時所采的動作稱之為 Activate,所以容易理解的,sessionDidActivate()與 sessionWillPassivate()分別于Activeate后與將Passivate前呼叫。


ServletRequestListener

[接口方法] requestInitialized()與 requestDestroyed()

[接收事件] RequestEvent

[觸發場景] 在request(HttpServletRequest)對象建立或被消滅時,會分別呼叫這兩個方法。


ServletRequestAttributeListener

[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()

[接收事件] HttpSessionBindingEvent

[觸發場景] 若有對象加入為request(HttpServletRequest)對象的屬性,則會呼叫attributeAdded(),同理在置換屬性與移除屬性時,會分別呼叫attributeReplaced()、 attributeRemoved()。


HttpSessionBindingListener

[接口方法] valueBound()與valueUnbound()

[接收事件] HttpSessionBindingEvent

[觸發場景] 實現HttpSessionBindingListener接口的類別,其實例如果被加入至session(HttpSession)對象的屬性中,則會呼叫 valueBound(),如果被從session(HttpSession)對象的屬性中移除,則會呼叫valueUnbound(),實現 HttpSessionBindingListener接口的類別不需在web.xml中設定。

實現上面這幾個接口的類別,除了HttpSessionBindingListener外,必須在web.xml中向容器注冊,容器才會在對應的事件發生時呼叫對應的類別,如

    < listener>   
          < listener-class >  
                 demo.servlet.listener.CustomServletContextListener    
          < /listener-class >  
    < /listener>  

    public class ListenerTest implements HttpSessionListener{

      Log log = LogFactorygetLog(getClass());  

      public void sessionCreated(HttpSessionEvent event){  
             httpSession session =event.getSession();  
             log.info("新建一個session,ID為"+session.getId());  
      }  

      public void sessionDestroyed(HttpSessionEvent event){  
             httpSession session =event.getSession();  
             log.info("銷毀一個session,ID為"+session.getId());  
      }  
}  </pre><br />
 本文由用戶 n672 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!