ServletContextListener 詳解

1.首先來看一看源碼 該類的源碼html

 

[java]  view plain  copy
 
  1. public interface ServletContextListener extends EventListener {  
  2.   
  3.     /** 
  4.      * Receives notification that the web application initialization 
  5.      * process is starting. 
  6.      * 
  7.      * <p>All ServletContextListeners are notified of context 
  8.      * initialization before any filters or servlets in the web 
  9.      * application are initialized. 
  10.      * 
  11.      * @param sce the ServletContextEvent containing the ServletContext 
  12.      * that is being initialized 
  13.      */  
  14.     public void contextInitialized(ServletContextEvent sce);  
  15.   
  16.     /** 
  17.      * Receives notification that the ServletContext is about to be 
  18.      * shut down. 
  19.      * 
  20.      * <p>All servlets and filters will have been destroyed before any 
  21.      * ServletContextListeners are notified of context 
  22.      * destruction. 
  23.      * 
  24.      * @param sce the ServletContextEvent containing the ServletContext 
  25.      * that is being destroyed 
  26.      */  
  27.     public void contextDestroyed(ServletContextEvent sce);  
  28. }  

 

此接口中提供了兩個方法,用於監聽ServletContext  的建立和銷燬,也就是監聽ServletContext 的生命週期,能夠說成是監聽Web 應用的生命週期,當web應用啓動後,就會觸發ServletContextEvent 事件 當此事件執行時,就會被ServletContextListener 監聽器監聽到,會調用他的 contextInitialized(ServletContextEvent sce)  方法,經過sce 能夠獲取ServletContext 實例,初始化一些數據,例如緩存的應用,如,建立數據庫鏈接,讀取數據庫數據,經過setAttribute(「」,obj) 方法設置數據,而後就是可經過servlet 獲取servletContext 的實例,經過getAttribute("") 獲取設置的數據java

實現代碼:web

 

[java]  view plain  copy
 
  1. public class MyContextListener implements ServletContextListener {  
  2.     private ServletContext context = null;  
  3.   
  4.     public void contextInitialized(ServletContextEvent event) {  
  5.         context = event.getServletContext();  
  6.         User user = DatabaseManager.getUserById(1);  
  7.         context.setAttribute("user1", user);  
  8.     }  
  9.    
  10.     public void contextDestroyed(ServletContextEvent event) {  
  11.         User user = (User)context.getAttribute("user1");  
  12.         DatabaseManager.updateUserData(user);  
  13.         this.context = null;  
  14.     }  
  15. }  


若是是web 項目 最後一步是使 ServletContext 生效,須要在web.xml 中配置監聽器,而且web.xml 把它放在正確的WEB-INF/classes目錄下,數據庫

 

[html]  view plain  copy
 
    1. <listener>  
    2.     <listener-class>MyServletContextListener</listener-class>  
    3. </listener>  
相關文章
相關標籤/搜索