ServletContext的講解

如何調用ServletContext:

一、實現ServletContextAware

二、request.getServletContext()

獲取WEB應用的初始化參數:

獲取context參數名:

僅有一個時:context.getInitParameterName();

有多個時:context.getInitParameterNames()

獲取Context參數值:

       context.getInitParameter(參數名);

注意:獲取context屬性時,一定要保證xml文件中有以下內容:

  1. <context-param>  
  2.        <param-name>參數名</param-name>  
  3.        <param-value>參數值</param-value>  
  4. </context-param>  
Servlet共享數據

有兩種方法:在定義context屬性和初始化request,初始化只能在jsp動態網頁上使用

   ·首先在request中定義context屬性即context.setAttribute(參數名,參數值),然後在RequestDispatcher中指定要跳轉到的url地址context.getAttribute(參數名)

//指定要跳轉到的頁面      使用相對路徑

RequestDispatcher rd = request.getRequestDispatcher("/success.html");

    //實現跳轉

    rd.forward(request, response);

·初始化request參數

   如:

[javascript] view plain copy
  1. //初始化request參數並實現跳轉  
  2. //request參數初始化          
  3. request.setAttribute("name""sunny");  
  4. //指定要跳轉到的頁面”  
  5.          RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");  
  6. //在後面添加“hahha  
  7.          response.getWriter().print("hahha");  
  8.          rd.include(request, response);  

forward和include區別:forward跳轉,include包含,加載jsp文件時,用include可將要添加的數據添加到已定義好的jsp文件中,用forward方法則不能實現這種功能

利用ServletContext對象讀取資源文件。

得到文件路徑

用context.getRealPath(指定文件)方法實現

如:

/*獲得ServletContext文件路徑

String path = context.getRealPath("");

讀取資源文件的三種方式:以properties文件(屬性文件)爲例

    ·context.getResource(String path)方法

      ·context.getRealPath(String path)方法

   ·context.getResourceAsStream(String path)方法

這三種方法基本相同,只是(一、三)兩種方法是獲取路徑後直接傳送到輸入流中;第二種是獲取路徑後先創建file文件,再將File文件傳入流中


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