JBOSS 點(diǎn)滴

          豐豐的博客

          ServletContextListener使用詳解 .

          摘自:http://blog.csdn.net/zhaozheng7758/article/details/6103700
          Servlet API 中有一個 ServletContextListener 接口,它能夠監(jiān)聽 ServletContext 對象的生命周期,實(shí)際上就是監(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 :如何實(shí)現(xiàn)在服務(wù)啟動的時候就動態(tài)的加入到里面的內(nèi)容:我們需要做的有:  

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

          2 )應(yīng)用項(xià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{ 

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

              public void contextDestroyed(ServletContextEvent sce) { 

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

              } 

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

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

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

          2 、在Web 應(yīng)用終止時把Web 應(yīng)用范圍內(nèi)的計(jì)數(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{

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

                 BufferedReader reader=new BufferedReader(

                     new InputStreamReader(context.

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

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

                 reader.close();

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

                 Counter counter=new Counter(count);

                 // 把計(jì)數(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)用范圍獲得計(jì)數(shù)器對象

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

                 if(counter!=null){

                 try{

                    // 把計(jì)數(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)體 閱讀(297) 評論(0)  編輯  收藏 所屬分類: Eclipse

          主站蜘蛛池模板: 乌拉特中旗| 怀化市| 收藏| 乌鲁木齐县| 台东县| 甘孜县| 商河县| 凯里市| 温州市| 惠水县| 安达市| 修武县| 固始县| 荥阳市| 太原市| 肃南| 宜兰市| 井陉县| 桓仁| 五寨县| 赞皇县| 大化| 镇巴县| 西吉县| 紫阳县| 碌曲县| 安仁县| 静安区| 前郭尔| 连江县| 岚皋县| 新绛县| 错那县| 吉安县| 仪陇县| 柯坪县| 湘西| 灵石县| 淮北市| 内乡县| 神农架林区|