Servlet入門學習(二)

Servletcontext 對象

1、ServletContext使用方法

this.getServletContext(); 
this.getServletConfig().getServletContext();

2、你可以把它想象成一張表,這個和Session非常相似:每一行就是一個屬性,如下:在這裏插入圖片描述
添加屬性:setAttribute(String name, Object obj);

得到值:getAttribute(String name),這個方法返回Object

刪除屬性:removeAttribute(String name)

3、生命週期

ServletContext中的屬性的生命週期從創建開始,到服務器關閉結束。

一個快速入門的案例:

我們創建Servlet1和Servlet2,分別用於在ServletContext中創建和讀取屬性:

Servlet1的doGet方法爲:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    // 獲取ServletContext對象的引用
    // 第一種方法

    ServletContext servletContext = this.getServletContext();
    // 第二種方法
    // ServletContext servletContext2 = this.getServletConfig().getServletContext();
    servletContext.setAttribute("name", "小明");
    out.println("將 name=小明  寫入了ServletContext");
}

Servlet2的doGet方法爲:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    // 取出ServletContext的某個屬性
    //1.首先獲取到ServletContext
    ServletContext servletContext = this.getServletContext();
    //2.取出屬性
    String name = (String)servletContext.getAttribute("name");
    out.println("name="+name);
}

以此訪問Servlet1和Servlet2,我們可以分別看到輸出如下:在這裏插入圖片描述
粗看之下,這個運行結果和Session,Cookie的應用似乎沒什麼區別,但事實上則完全不一樣的。只要不關閉Tomcat或者reload該應用,當我們關閉當前的瀏覽器,或者是換一個瀏覽器,比如從360瀏覽器換到了IE瀏覽器再次訪問Servlet2,我們依然可以看到這個結果!這就是和和Session,Cookie最大的不同了。之所以會造成這種不同,是因爲ServletContext存在於服務器內存中的一個公共空間,它可以供所有的用戶客戶端訪問。

ServletContext應用

1、多個Servlet可以通過ServletContext對象來實現數據間的共享

類似於Session,通過ServletContext對象我們也可以實現數據共享,但值得注意的是,Session是隻能在一個客戶端中共享數據,而ServletContext中的數據是在所有客戶端中都可以實現數據共享的。

2、實現Servlet的請求轉發

之前我們學過的請求轉發是通過request對象的:

request.getRequestDispatcher("/url").forward(request, response);

這裏要說明的是,ServletContext也可以實現請求轉發:

this.getServletContext().getRequestDispatcher("/url").forward(request, response); 

這兩個轉發效果是一樣的。

3、獲取Web應用的初始化參數

我們可以用標籤爲servlet配置初始化參數,然後使用ServletConfig對象獲取這些參數,假如有如下的MyServlet,它的配置爲:

<servlet>  
    <servlet-name>MyServlet</servlet-name>  
    <servlet-class>com.gavin.servlet.MyServlet</servlet-class>  
    <init-param>  
        <param-name>encoding</param-name>  
        <param-value>utf-8</param-value>  
    </init-param>  
</servlet>  

可以看到它配置了一個初始化參數:encoding=utf-8,那麼我們在MyServlet的源代碼中需要這樣去得到這個參數:

String encoding = this.getServletConfig().getInitParameter("encoding");

注意,上述的參數配置方法只針對一個特定的Servlet有效,我們可以通過ServletContext來獲取全局的、整個Web應用的初始化參數,全局的初始化參數是這樣配置在web.xml文件中的:

<!-- 如果希望所有的Servlet都可以使用該配置,則必須這麼做 -->
<context-param>
    <param-name>name</param-name>
    <param-value>gavin</param-value>
</context-param>

然後我們可以在任意一個Servlet中使用ServletContext獲取這個參數:

String name = this.getServletContext().getInitParameter("name");

4、利用ServletContext對象讀取資源文件(比如properties文件)

讀取資源文件要根據資源文件所在的位置來決定,一般分爲以下兩種情況:

4.1:文件在WebRoot文件夾下,即Web應用的根目錄。這時候我們可以使用ServletContext來讀取該資源文件。

假設我們Web根目錄下有一個配置數據庫信息的dbinfo.properties文件,裏面配置了name和password屬性,這時候可以通過ServletContext去讀取這個文件:

// 這種方法的默認讀取路徑就是Web應用的根目錄
InputStream stream = this.getServletContext().getResourceAsStream("dbinfo.properties");
// 創建屬性對象
Properties properties = new Properties();
properties.load(stream);
String name = properties.getProperty("name");
String password = properties.getProperty("password");
out.println("name="+name+";password="+password);

4.2:如果這個文件放在了src目錄下,這時就不能用ServletContext來讀取了,必須要使用類加載器去讀取。

// 類加載器的默認讀取路徑是src根目錄

InputStream stream = MyServlet.class.getClassLoader().getResourceAsStream("dbinfo.properties")

如果這個文件此時還沒有直接在src目錄下,而是在src目錄下的某個包下,比如在com.gavin包下,此時類加載器要加上包的路徑,如下:

InputStream stream = MyServlet.class.getClassLoader().getResourceAsStream("com/gavin/dbinfo.properties")

補充一點,ServletContext只有在讀取的文件在web應用的根目錄下時,才能獲取文件的全路徑。比如我們在WebRoot文件夾下有一個images文件夾,images文件夾下有一個Servlet.jpg圖片,爲了得到這個圖片的全路徑,如下:

// 如何讀取到一個文件的全路徑,這裏會得到在Tomcat的全路徑

String path = this.getServletContext().getRealPath("/images/Servlet.jpg");

在網站開發中,有很多功能要使用ServletContext,比如

  1. 網站計數器

  2. 網站的在線用戶顯示

  3. 簡單的聊天系統

總之,如果是涉及到不同用戶共享數據,而這些數據量不大,同時又不希望寫入數據庫中,我們就可以考慮使用ServletContext實現。

ServletContext使用建議

因爲存在ServletContext中的數據在服務器中會長時間,這樣就會佔用很多內存,因此在使用ServletContext時,建議不要往裏面添加過大的數據!

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