ServletContextListener使用詳解(監聽Tomcat啓動、關閉)

在 Servlet API 中有一個 ServletContextListener 接口,它能夠監聽 ServletContext 對象的生命週期,實際上就是監聽 Web 應用的生命週期。

  當Servlet 容器啓動或終止Web 應用時,會觸發ServletContextEvent 事件,該事件由ServletContextListener 來處理。在 ServletContextListener 接口中定義了處理ServletContextEvent 事件的兩個方法。

java代碼
 

/**
 * 當Servlet 容器啓動Web 應用時調用該方法。在調用完該方法之後,容器再對Filter 初始化,
 * 並且對那些在Web 應用啓動時就需要被初始化的Servlet 進行初始化。
 */
contextInitialized(ServletContextEvent sce) 
 
 
/**
 * 當Servlet 容器終止Web 應用時調用該方法。在調用該方法之前,容器會先銷燬所有的Servlet 和Filter 過濾器。
 */
contextDestroyed(ServletContextEvent sce)

下面通過兩個具體的例子來介紹 ServletContextListener 的用法。

例一:在服務啓動時,將數據庫中的數據加載進內存,並將其賦值給一個屬性名,其它的 Servlet 就可以通過 getAttribute 進行屬性值的訪問。

  有如下兩個步驟:

 

1、ServletContext 對象是一個爲整個 web 應用提供共享的內存,任何請求都可以訪問裏面的內容

 

2、如何實現在服務啓動的時候就動態的加入到裏面的內容:我們需要做的有:  

1 ) 實現 servletContextListerner 接口 並將要共享的通過 setAttribute ( name,data )方法提交到內存中去   ;

2 )應用項目通過 getAttribute(name) 將數據取到 。

java代碼

public class ServletContextLTest implements ServletContextListener{ 
 
    // 實現其中的銷燬函數
    
    public void contextDestroyed(ServletContextEvent sce) { 
 
        System.out.println("this is last destroyeed");    
 
    } 
 
    // 實現其中的初始化函數,當有事件發生時即觸發
 
    public void contextInitialized(ServletContextEvent sce) { 
 
        ServletContext sct=sce.getServletContext(); 
 
        Map<Integer,String> depts=new HashMap<Integer,String>(); 
 
        Connection connection=null; 
 
        PreparedStatement pstm=null; 
 
        ResultSet rs=null; 
 
         
 
        try{ 
 
            connection=ConnectTool.getConnection(); 
 
            String sql="select deptNo,dname from dept"; 
 
            pstm=connection.prepareStatement(sql); 
 
            rs=pstm.executeQuery(); 
 
            while(rs.next()){ 
 
                depts.put(rs.getInt(1), rs.getString(2)); 
 
            } 
 
            // 將所取到的值存放到一個屬性鍵值對中
 
            sct.setAttribute("dept", depts); 
 
            System.out.println("======listener test is beginning========="); 
 
        }catch(Exception e){ 
 
            e.printStackTrace(); 
 
        }finally{ 
 
            ConnectTool.releasersc(rs, pstm, connection); 
 
        } 
 
    } 
 
}

在完成上述編碼後,仍需在 web.xml 中進行如下配置,以使得該監聽器可以起作用。

Xml代碼

1 <listener> 

3    <listener-class>ServletContextTest.ServletContextLTest</listener-class> 

5 </listener>  
在完成上述配置後, web 服務器在啓動時,會直接加載該監聽器,通過以下的應用程序就可以進行數據的訪問。

Java代碼

public class CreateEmployee extends HttpServlet{ 
 
    @Override 
 
    protected void service(HttpServletRequest request, HttpServletResponse response) 
 
            throws ServletException, IOException { 
 
        ServletContext sct=getServletConfig().getServletContext(); 
 
        // 從上下文環境中通過屬性名獲取屬性值
 
        Map<Integer,String> dept=(Map<Integer,String>)sct.getAttribute("dept"); 
 
        Set<Integer> key=dept.keySet(); 
 
        response.setContentType("text/html;charset=utf-8"); 
 
        PrintWriter out=response.getWriter(); 
 
        out.println("<html>"); 
 
        out.println("<body>"); 
 
        out.println("<form action='/register' action='post'>"); 
 
        out.println("<table alignb='center'>"); 
 
        out.println("<tr>"); 
 
        out.println("<td>"); 
 
        out.println("username:"); 
 
        out.println("</td>"); 
 
        out.println("<td>"); 
 
        out.println("<input type='text' name='username'"); 
 
        out.println("</tr>"); 
 
        out.println("<tr>"); 
 
        out.println("<td>"); 
 
        out.println("city:"); 
 
        out.println("</td>"); 
 
        out.println("<td>"); 
 
        out.println("<select name='dept'"); 
 
        for(Integer i:key){ 
 
            out.println("<option value='"+i+"'>"+dept.get(i)+"</option>"); 
 
        } 
 
        out.println("</select>"); 
 
        out.println("</td>"); 
 
        out.println("<tr>"); 
 
        out.println("</table>"); 
 
        out.println("</form>"); 
 
        out.println("</body>"); 
 
        out.println("</html>"); 
 
        out.flush(); 
 
    } 
 
}

例二:書寫一個類用於統計當Web 應用啓動後,網頁被客戶端訪問的次數。如果重新啓動Web 應用,計數器不會重新從1 開始統計訪問次數,而是從上次統計的結果上進行累加。

 

在實際應用中,往往需要統計自Web 應用被髮布後網頁被客戶端訪問的次數,這就要求當Web 應用被終止時,計數器的數值被永久存儲在一個文件中或者數據庫中,等到Web 應用重新啓動時,先從文件或數據庫中讀取計數器的初始值,然後在此基礎上繼續計數。

 

向文件中寫入或讀取計數器的數值的功能可以由自定義的 MyServletContextListener 類來完成,它具有以下功能:

 

1 、在 Web 應用啓動時從文件中讀取計數器的數值,並把表示計數器的 Counter 對象存放到 Web應用範圍內。存放計數器的文件的路徑爲helloapp/count/count.txt 。

2 、在Web 應用終止時把Web 應用範圍內的計數器的數值保存到count.txt 文件中。

Java代碼
 

public class MyServletContextListener implements ServletContextListener{
 
  public void contextInitialized(ServletContextEvent sce){
 
    System.out.println("helloapp application is Initialized.");
 
    // 獲取 ServletContext 對象
 
    ServletContext context=sce.getServletContext();
 
    try{
 
       // 從文件中讀取計數器的數值
 
       BufferedReader reader=new BufferedReader(
 
           new InputStreamReader(context.
 
           getResourceAsStream("/count/count.txt")));
 
       int count=Integer.parseInt(reader.readLine());
 
       reader.close();
 
       // 創建計數器對象
 
       Counter counter=new Counter(count);
 
       // 把計數器對象保存到 Web 應用範圍
 
       context.setAttribute("counter",counter);
 
       } catch(IOException e) {
 
          e.printStackTrace();
 
       }
 
   }
 
   public void contextDestroyed(ServletContextEvent sce){
 
       System.out.println("helloapp application is Destroyed.");
 
       // 獲取 ServletContext 對象
 
       ServletContext context=sce.getServletContext();
 
       // 從 Web 應用範圍獲得計數器對象
 
       Counter counter=(Counter)context.getAttribute("counter");
 
       if(counter!=null){
 
       try{
 
          // 把計數器的數值寫到 count.txt 文件中
 
          String filepath=context.getRealPath("/count");
 
          filepath=filepath+"/count.txt";
 
          PrintWriter pw=new PrintWriter(filepath);
 
          pw.println(counter.getCount());
 
          pw.close();
 
         } catch(IOException e) {
 
             e.printStackTrace();
 
         }
 
     }
 
   }
 
}

將用戶自定義的 MyServletContextListener 監聽器在 Servlet 容器進行註冊, Servlet 容器會在啓動或終止 Web 應用時,會調用該監聽器的相關方法。在 web.xml 文件中, <listener> 元素用於向容器註冊監聽器:

<listener>
     <listenerclass>
         ServletContextTest.MyServletContextListener
    <listener-class/>
</listener>     

通過上述兩個例子,即可以非常清楚的瞭解到 ServletContextListener 接口的使用方法及技巧。

在Container 加載Web 應用程序時(例如啓動 Container 之後),會呼叫contextInitialized() ,而當容器移除Web 應用程序時,會呼叫contextDestroyed () 方法。

通過 Tomcat 控制檯的打印結果的先後順序,會發現當 Web 應用啓動時,Servlet 容器先調用contextInitialized() 方法,再調用lifeInit 的init() 方法;

當Web 應用終止時,Servlet 容器先調用lifeInit 的destroy() 方法,再調用contextDestroyed() 方法。

由此可見,在Web 應用的生命週期中,ServletContext 對象最早被創建,最晚被銷燬。

public class DSAction extends Thread implements ServletContextListener {
 
    public void contextInitialized(ServletContextEvent arg0) {
        
        super.start();// 啓動一個線程
    }
    public void zdfs() throws IOException {
 
        Huoquzhuye u = new Huoquzhuye();// 爬蟲方法類
        Htmlneirong h = new Htmlneirong();// 存入數據庫類
        List<String> list = u.seturl("http://xxxxxxx");
        for (int i = 0; i < list.size(); i++) {
            String txt = list.get(i).substring(0, 22);
            String start = list.get(i).substring(4, 14);
            String end = list.get(i).substring(22, list.get(i).length());
            try {
                h.seturl(txt, start, end);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
 
                e.printStackTrace();
            }
        }
 
    }
 
    @Override
    public void run() {
        while (true) {
            try {
                this.zdfs();
                super.sleep(1000 * 60 * 10);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
 
    /*
     * (non-Javadoc)
     * 
     * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
     * ServletContextEvent)
     */
 
 
    /*
     * (non-Javadoc)
     * 
     * @see
     * javax.servlet.ServletContextListener#contextInitialized(javax.servlet
     * .ServletContextEvent)
     */
 
    public void contextDestroyed(ServletContextEvent arg0) {
        super.stop();// 停止線程
 
    }
}

web.xml

1  <listener>
2   <listener-class>bj.hbj.dingshi.DSAction</listener-class>
3 </listener>
1、調用super.start()開啓線程。

2、最後關閉線程super.stop()。
————————————————
版權聲明:本文爲CSDN博主「海天依色」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/zhaoxb006/article/details/44017359

發佈了55 篇原創文章 · 獲贊 72 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章