ServletContext詳解

ServletContext詳解


一個項目只有一個ServletContext對象!

我們可以在N多個Servlet中來獲取這個唯一的對象,使用它可以給多個Servlet傳遞數據!

與天地同壽!!!這個對象在Tomcat啓動時就創建,在Tomcat關閉時纔會死去!

 

 

1ServletContext概述

服務器會爲每個應用創建一個ServletContext對象:

l ServletContext對象的創建是在服務器啓動時完成的;

l ServletContext對象的銷燬是在服務器關閉時完成的。

 

   ServletContext對象的作用是在整個Web應用的動態資源之間共享數據!例如在AServlet中向ServletContext對象中保存一個值,然後在BServlet中就可以獲取這個值,這就是共享數據了。

 

2 獲取ServletContext

ServletConfig#getServletContext()

GenericServlet#getServletContext();

HttpSession#getServletContext()

ServletContextEvent#getServletContext()

 

 

Servlet中獲取ServletContext對象:

l 在void init(ServletConfig config)中:ServletContext context = config.getServletContext();ServletConfig類的getServletContext()方法可以用來獲取ServletContext對象;

GenericeServletHttpServlet中獲取ServletContext對象:

l GenericServlet類有getServletContext()方法,所以可以直接使用this.getServletContext()來獲取;

  

public class MyServlet implements Servlet {

public void init(ServletConfig config) {

    ServletContext context = config.getServletContext();

}

}

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) {

    ServletContext context = this.getServletContext();

}

}

 

3 域對象的功能

ServletContextJavaWeb四大域對象之一:

l PageContext

l ServletRequest

l HttpSession

l ServletContext

所有域對象都有存取數據的功能,因爲域對象內部有一個Map,用來存儲數據,下面是ServletContext對象用來操作數據的方法:

l void setAttribute(String name, Object value):用來存儲一個對象,也可以稱之爲存儲一個域屬性,例如:servletContext.setAttribute(“xxx”, “XXX”),在ServletContext中保存了一個域屬性,域屬性名稱爲xxx,域屬性的值爲XXX。請注意,如果多次調用該方法,並且使用相同的name,那麼會覆蓋上一次的值,這一特性與Map相同;

l Object getAttribute(String name):用來獲取ServletContext中的數據,當前在獲取之前需要先去存儲才行,例如:String value = (String)servletContext.getAttribute(“xxx”);,獲取名爲xxx的域屬性;

l void removeAttribute(String name):用來移除ServletContext中的域屬性,如果參數name指定的域屬性不存在,那麼本方法什麼都不做;

l Enumeration getAttributeNames():獲取所有域屬性的名稱;

 

4 獲取應用初始化參數

Servlet也可以獲取初始化參數,但它是局部的參數;也就是說,一個Servlet只能獲取自己的初始化參數,不能獲取別人的,即初始化參數只爲一個Servlet準備!

可以配置公共的初始化參數,爲所有Servlet而用!這需要使用ServletContext才能使用!

還可以使用ServletContext來獲取在web.xml文件中配置的應用初始化參數!注意,應用初始化參數與Servlet初始化參數不同:

web.xml

<web-app ...>

  ...

  <context-param>

<param-name>paramName1</param-name>

<param-value>paramValue1</param-value>  

  </context-param>

  <context-param>

<param-name>paramName2</param-name>

<param-value>paramValue2</param-value>  

  </context-param>

</web-app>

ServletContext context = this.getServletContext();

String value1 = context.getInitParameter("paramName1");

String value2 = context.getInitParameter("paramName2");

System.out.println(value1 + ", " + value2);

Enumeration names = context.getInitParameterNames();

while(names.hasMoreElements()) {

System.out.println(names.nextElement());

}

 

5 獲取資源相關方法

 

5.1 獲取真實路徑(*****

還可以使用ServletContext對象來獲取Web應用下的資源,例如在hello應用的根目錄下創建a.txt文件,現在想在Servlet中獲取這個資源,就可以使用ServletContext來獲取。

 

l 獲取a.txt的真實路徑:String realPath = servletContext.getRealPath(“/a.txt”)realPath的值爲a.txt文件的絕對路徑:F:\tomcat6\webapps\hello\a.txt;

l 獲取b.txt的真實路徑:String realPath = servletContext.getRealPath(“/WEB-INF/b.txt”)

 

5.2 獲取資源流

不只可以獲取資源的路徑,還可以通過ServletContext獲取資源流,即把資源以輸入流的方式獲取:

l 獲取a.txt資源流:InputStream in = servletContext.getResourceAsStream(“/a.txt”)

l 獲取b.txt資源流:InputStream in = servletContext.getResourceAsStream(“/WEB-INF/b.txt”)

 

5.3 獲取指定目錄下所有資源路徑

還可以使用ServletContext獲取指定目錄下所有資源路徑,例如獲取/WEB-INF下所有資源的路徑:

Set set = context.getResourcePaths("/WEB-INF");

System.out.println(set);

[/WEB-INF/lib/, /WEB-INF/classes/, /WEB-INF/b.txt, /WEB-INF/web.xml]

 

注意,本方法必須以“/”開頭!!!

 

6 練習:訪問量統計

一個項目中所有的資源被訪問都要對訪問量進行累加!

創建一個int類型的變量,用來保存訪問量,然後把它保存到ServletContext的域中,這樣可以保存所有的Servlet都可以訪問到!

最初時,ServletContext中沒有保存訪問量相關的屬性;

當本站第一次被訪問時,創建一個變量,設置其值爲1;保存到ServletContext中;

當以後的訪問時,就可以從ServletContext中獲取這個變量,然後在其基礎之上加1。

 

 

獲取ServletContext對象,查看是否存在名爲count的屬性,如果存在,說明不是第一次訪問,如果不存在,說明是第一次訪問;

Ø 第一次訪問:調用ServletcontextsetAttribute()傳遞一個屬性,名爲count,值爲1

Ø 2~N次訪問:調用ServletContextgetAttribute()方法獲取原來的訪問量,給訪問量加1,再調用ServletcontextsetAttribute()方法完成設置。

 

 

相信各位一定見過很多訪問量統計的網站,即“本頁面被訪問過XXX次”。因爲無論是哪個用戶訪問指定頁面,都會累計訪問量,所以這個訪問量統計應該是整個項目共享的!很明顯,這需要使用ServletContext來保存訪問量。

  1. ServletContext application  = this.getServletContext();  
  2. Integer count = (Integer)application.getAttribute("count");  
  3. if(count == null) {  
  4. count = 1;  
  5. else {  
  6. count++;  
  7. }  
  8. response.setContentType("text/html;charset=utf-8");  
  9. response.getWriter().print("<h1>本頁面一共被訪問" + count + "次!</h1>");  
  10. application.setAttribute("count", count);  
ServletContext application  = this.getServletContext();
Integer count = (Integer)application.getAttribute("count");
if(count == null) {
count = 1;
} else {
count++;
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("<h1>本頁面一共被訪問" + count + "次!</h1>");
application.setAttribute("count", count);



 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章