Java深刻 - WEB容器監聽器詳解 ServletContextListener

WEB容器監聽器ServletContextListener主要用來監聽容器啓動和 銷燬的時候須要作一些操做,就能夠使用這個監聽器來作。web

ServletContextListener在Spring啓動前啓動。
api


咱們實現一個簡單的監聽器,須要繼承接口ServletContextListener:app

  1.  * 一個測試的監聽器例子  ide

  2.  * @author  zhuli  測試

  3.  * @date 2014-7-26  spa

  4.  */  .net

  5. public class TestContextLister implements ServletContextListener {  日誌

  6.   

  7.     @Override  orm

  8.     public void contextInitialized(ServletContextEvent sce) {  xml

  9.         System.out.println("==============================容器裝載");  

  10.   

  11.     }  

  12.   

  13.     @Override  

  14.     public void contextDestroyed(ServletContextEvent sce) {  

  15.         System.out.println("==============================容器銷燬");  

  16.     }  

  17.   

  18. }  

ServletContextListener 實現兩個接口,一個是容器啓動的時候,一個是容器銷燬的時候:

  1. public interface ServletContextListener extends EventListener {  

  2.     /** 

  3.      ** Notification that the web application initialization 

  4.      ** process is starting. 

  5.      ** All ServletContextListeners are notified of context 

  6.      ** initialization before any filter or servlet in the web 

  7.      ** application is initialized. 

  8.      */  

  9.   

  10.     public void contextInitialized ( ServletContextEvent sce );  

  11.   

  12.     /** 

  13.      ** Notification that the servlet context is about to be shut down. 

  14.      ** All servlets and filters have been destroy()ed before any 

  15.      ** ServletContextListeners are notified of context 

  16.      ** destruction. 

  17.      */  

  18.     public void contextDestroyed ( ServletContextEvent sce );  

  19. }  


在web.xml中的配置:

  1. <listener>  

  2.     <listener-class>com.xxx.controller.web.TestContextLister</listener-class>  

  3. </listener>  


容器啓動後,會在容器啓動的日誌中看到:

  1. ==============================容器裝載  

  2. 2014-07-26 08:54:01.302:INFO:/:Initializing Spring FrameworkServlet 'apiServlet'

相關文章
相關標籤/搜索