如何調用ServletContext:
一、實現ServletContextAware
二、request.getServletContext()
獲取WEB應用的初始化參數:
獲取context參數名:
僅有一個時:context.getInitParameterName();
有多個時:context.getInitParameterNames()
獲取Context參數值:
context.getInitParameter(參數名);
注意:獲取context屬性時,一定要保證xml文件中有以下內容:
- <context-param>
- <param-name>參數名</param-name>
- <param-value>參數值</param-value>
- </context-param>
有兩種方法:在定義context屬性和初始化request,初始化只能在jsp動態網頁上使用
·首先在request中定義context屬性即context.setAttribute(參數名,參數值),然後在RequestDispatcher中指定要跳轉到的url地址context.getAttribute(參數名)
//指定要跳轉到的頁面 使用相對路徑
RequestDispatcher rd = request.getRequestDispatcher("/success.html");
//實現跳轉
rd.forward(request, response);
·初始化request參數
如:
- //初始化request參數並實現跳轉
- //request參數初始化
- request.setAttribute("name", "sunny");
- //指定要跳轉到的頁面”
- RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
- //在後面添加“hahha
- response.getWriter().print("hahha");
- 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文件傳入流中