<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    JBOSS 點滴

    豐豐的博客

    ServletContextListener使用詳解 .

    摘自:http://blog.csdn.net/zhaozheng7758/article/details/6103700
    Servlet API 中有一個 ServletContextListener 接口,它能夠監(jiān)聽 ServletContext 對象的生命周期,實際上就是監(jiān)聽 Web 應(yīng)用的生命周期。

    當(dāng)Servlet 容器啟動或終止Web 應(yīng)用時,會觸發(fā)ServletContextEvent 事件,該事件由 ServletContextListener 來處理。在 ServletContextListener 接口中定義了處理ServletContextEvent 事件的兩個方法。

    l  contextInitialized(ServletContextEvent sce) :當(dāng)Servlet 容器啟動Web 應(yīng)用時調(diào)用該方法。在調(diào)用完該方法之后,容器再對Filter 初始化,并且對那些在Web 應(yīng)用啟動時就需要被初始化的Servlet 進(jìn)行初始化。

    l  contextDestroyed(ServletContextEvent sce) :當(dāng)Servlet 容器終止Web 應(yīng)用時調(diào)用該方法。在調(diào)用該方法之前,容器會先銷毀所有的ServletFilter 過濾器。

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

    例一:在服務(wù)啟動時,將數(shù)據(jù)庫中的數(shù)據(jù)加載進(jìn)內(nèi)存,并將其賦值給一個屬性名,其它的 Servlet 就可以通過 getAttribute 進(jìn)行屬性值的訪問。有如下兩個步驟:

    1 ServletContext 對象是一個為整個 web 應(yīng)用提供共享的內(nèi)存,任何請求都可以訪問里面的內(nèi)容  

    2 :如何實現(xiàn)在服務(wù)啟動的時候就動態(tài)的加入到里面的內(nèi)容:我們需要做的有:  

    1 實現(xiàn) servletContextListerner 接口 并將要共享的通過 setAttribute name,data )方法提交到內(nèi)存中去  

    2 )應(yīng)用項目通過 getAttribute(name) 將數(shù)據(jù)取到

    package ServletContextTest; 

     

    import java.sql.Connection; 

    import java.sql.PreparedStatement; 

    import java.sql.ResultSet; 

    import java.util.HashMap; 

    import java.util.Map; 

     

    import javax.servlet.ServletContext; 

    import javax.servlet.ServletContextEvent; 

    import javax.servlet.ServletContextListener; 

     

    import util.ConnectTool; 

     

    public class ServletContextLTest implements ServletContextListener{ 

        // 實現(xiàn)其中的銷毀函數(shù)

        public void contextDestroyed(ServletContextEvent sce) { 

            System.out.println("this is last destroyeed");    

        } 

        // 實現(xiàn)其中的初始化函數(shù),當(dāng)有事件發(fā)生時即觸發(fā)

        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 中進(jìn)行如下配置,以使得該監(jiān)聽器可以起作用。

    <listener> 

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

    </listener> 

    在完成上述配置后, web 服務(wù)器在啟動時,會直接加載該監(jiān)聽器,通過以下的應(yīng)用程序就可以進(jìn)行數(shù)據(jù)的訪問。

    package ServletContextTest; 

    import java.io.IOException; 

    import java.io.PrintWriter; 

    import java.util.*; 

    import javax.servlet.ServletContext; 

    import javax.servlet.ServletException; 

    import javax.servlet.http.HttpServlet; 

    import javax.servlet.http.HttpServletRequest; 

    import javax.servlet.http.HttpServletResponse; 

    public class CreateEmployee extends HttpServlet{ 

     

        @Override 

        protected void service(HttpServletRequest request, HttpServletResponse response) 

                throws ServletException, IOException { 

            ServletContext sct=getServletConfig().getServletContext(); 

    // 從上下文環(huán)境中通過屬性名獲取屬性值

            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(); 

        } 

    例二:書寫一個類用于統(tǒng)計當(dāng)Web 應(yīng)用啟動后,網(wǎng)頁被客戶端訪問的次數(shù)。如果重新啟動Web 應(yīng)用,計數(shù)器不會重新從1 開始統(tǒng)計訪問次數(shù),而是從上次統(tǒng)計的結(jié)果上進(jìn)行累加。在實際應(yīng)用中,往往需要統(tǒng)計自Web 應(yīng)用被發(fā)布后網(wǎng)頁被客戶端訪問的次數(shù),這就要求當(dāng)Web 應(yīng)用被終止時,計數(shù)器的數(shù)值被永久存儲在一個文件中或者數(shù)據(jù)庫中,等到Web 應(yīng)用重新啟動時,先從文件或數(shù)據(jù)庫中讀取計數(shù)器的初始值,然后在此基礎(chǔ)上繼續(xù)計數(shù)。

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

    1 、在 Web 應(yīng)用啟動時從文件中讀取計數(shù)器的數(shù)值,并把表示計數(shù)器的 Counter 對象存放到 Web 應(yīng)用范圍內(nèi)。存放計數(shù)器的文件的路徑為helloapp/count/count.txt

    2 、在Web 應(yīng)用終止時把Web 應(yīng)用范圍內(nèi)的計數(shù)器的數(shù)值保存到count.txt 文件中。

    package ServletContextTest; 

    import javax.servlet.ServletContext; 

    import javax.servlet.ServletContextEvent; 

    import javax.servlet.ServletContextListener; 

    public class MyServletContextListener implements ServletContextListener{

      public void contextInitialized(ServletContextEvent sce){

        System.out.println("helloapp application is Initialized.");

        // 獲取 ServletContext 對象

        ServletContext context=sce.getServletContext();

        try{

           // 從文件中讀取計數(shù)器的數(shù)值

           BufferedReader reader=new BufferedReader(

               new InputStreamReader(context.

               getResourceAsStream("/count/count.txt")));

           int count=Integer.parseInt(reader.readLine());

           reader.close();

           // 創(chuàng)建計數(shù)器對象

           Counter counter=new Counter(count);

           // 把計數(shù)器對象保存到 Web 應(yīng)用范圍

           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 應(yīng)用范圍獲得計數(shù)器對象

           Counter counter=(Counter)context.getAttribute("counter");

           if(counter!=null){

           try{

              // 把計數(shù)器的數(shù)值寫到 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 監(jiān)聽器在 Servlet 容器進(jìn)行注冊, Servlet 容器會在啟動或終止 Web 應(yīng)用時,會調(diào)用該監(jiān)聽器的相關(guān)方法。在 web.xml 文件中, <listener> 元素用于向容器注冊監(jiān)聽器:

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

    通過上述兩個例子,即可以非常清楚的了解到 ServletContextListener 接口的使用方法及技巧。 Container 加載Web 應(yīng)用程序時(例如啟動 Container 之后),會呼叫contextInitialized() ,而當(dāng)容器移除Web 應(yīng)用程序時,會呼叫contextDestroyed () 方法。 通過 Tomcat 控制臺的打印結(jié)果的先后順序,會發(fā)現(xiàn)當(dāng) Web 應(yīng)用啟動時,Servlet 容器先調(diào)用contextInitialized() 方法,再調(diào)用lifeInitinit() 方法;當(dāng)Web 應(yīng)用終止時,Servlet 容器先調(diào)用lifeInitdestroy() 方法,再調(diào)用contextDestroyed() 方法。由此可見,在Web 應(yīng)用的生命周期中,ServletContext 對象最早被創(chuàng)建,最晚被銷毀。  

    posted on 2013-11-20 10:13 半導(dǎo)體 閱讀(295) 評論(0)  編輯  收藏 所屬分類: Eclipse

    主站蜘蛛池模板: 青青青国产色视频在线观看国产亚洲欧洲国产综合 | 在线观看免费污视频| 无码国产精品一区二区免费vr| 麻豆一区二区三区蜜桃免费| 亚洲人成网男女大片在线播放| 亚洲高清视频在线播放| 久久亚洲国产视频| 亚洲人JIZZ日本人| 在线观看亚洲精品福利片| 亚洲精品乱码久久久久久不卡 | 亚洲伊人久久大香线蕉影院| 亚洲国产精品无码专区影院| 亚洲伊人久久精品影院| 亚洲国产精品尤物YW在线观看| 在线a人片天堂免费观看高清| 18国产精品白浆在线观看免费 | 亚洲第一男人天堂| 亚洲国产人成在线观看| 中文字幕亚洲精品资源网| 久久青青成人亚洲精品| 国产l精品国产亚洲区在线观看| 亚洲尤码不卡AV麻豆| 亚洲日产韩国一二三四区| 亚洲无线码一区二区三区| 在线精品亚洲一区二区小说| 亚洲一区日韩高清中文字幕亚洲| 免费国内精品久久久久影院| 国产免费黄色大片| 一区二区三区亚洲视频| JLZZJLZZ亚洲乱熟无码| 成人午夜亚洲精品无码网站| 亚洲色精品vr一区二区三区 | 国产成人无码区免费内射一片色欲 | 成人AV免费网址在线观看| 青青草a免费线观a| 成人在线免费观看| 一区二区三区亚洲视频| 国产亚洲av人片在线观看| 亚洲高清在线播放| 亚洲国产日韩女人aaaaaa毛片在线| 亚洲中文字幕人成乱码 |