一、什么是ServletContext
- ServletContext代表是一個web應用的上下文對象(web應用對象)
- 里面封裝的都是web應用信息
- 一個ServletContext對應一個應用
二、ServletContext的生命周期
- 在服務器一啟動的時候就會創建
- 在服務器關閉的時候銷毀
三、如何獲得上下文
- 通過init方法當中一個參數ServletConfig來獲取
public void init(ServletConfig config) throws ServletException {
System.out.println(config);
ServletContext context = config.getServletContext();
System.out.println(context);
}
/** 運行結果
* org.apache.catalina.core.StandardWrapperFacade@3e478880
* org.apache.catalina.core.ApplicationContextFacade@24391b1e
*/
- 直接在HttpServlet當中獲取
- this.getServletContext
- 這種方法本質還是通過config來去獲取的
四、獲取全局的初始化參數
初始化參數不能再某一個Servlet當中來去配置。在最外層來去配置
獲取全局初始化參數
五、獲得Web應用中某一個資源的絕對路徑
各文件的結構
獲取 WebContent 下的文件
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String realPatha = context.getRealPath("a.txt");
System.out.println(realPatha);
String realPathb = context.getRealPath("WEB-INF/b.txt");
System.out.println(realPathb);
}
獲取 Java Resources 下的文件
- 方法一:和獲取 WebContent 下的文件一樣,先獲取根目錄,然后拼接。
- 方法二:通過類加載器獲取字節碼目錄
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String pathc = one.class.getClassLoader().getResource("c.txt").getPath();
System.out.println(pathc);
// 解決路徑中 空格顯示為 %20
pathc = URLDecoder.decode(pathc, "utf-8");
System.out.println(pathc);
String pathd = one.class.getClassLoader().getResource("com/xzh/servlet/d.txt").getPath();
pathd = URLDecoder.decode(pathd, "utf-8");
System.out.println(pathd);
String pathe = one.class.getClassLoader().getResource("e.txt").getPath();
pathe = URLDecoder.decode(pathe, "utf-8");
System.out.println(pathe);
}
六、ServletContext是一個域對象
- 域 :能夠存儲數據。
- 域對象 :能夠存取數據數據就的對象。
ServletContext域對象的作用范圍:
- 整個web應用,所有的web資源都可以進行存取數據
- 數據是可以共享的
獲取完ServletContext之后向里面寫數據
context.setAttribute(String name,Object value);
獲取完ServletContext之后,通過name取出存放的數據
context.getAttribute(String name);
獲取完ServletContext之后,刪除指定名稱的值
Context.removeAttribute(String name);