ServletContext物件--三大域物件
阿新 • • 發佈:2020-11-03
Servlet三大域物件的應用 request、session、application(ServletContext)
ServletContext是一個全域性的儲存資訊的空間,伺服器開始就存在,伺服器關閉才釋放。
request,一個使用者可有多個;session,一個使用者一個;而servletContext,所有使用者共用一個。所以,為了節省空間,提高效率,ServletContext中,要放必須的、重要的、所有使用者需要共享的執行緒又是安全的一些資訊。
1.獲取servletcontext物件:
ServletContext sc = null; sc = request.getSession().getServletContext(); //或者使用 //ServletContext sc = this.getServletContext(); System.out.println("sc=" + sc);
2.方法:
域物件,獲取全域性物件中儲存的資料:
所有使用者共用一個
servletDemo1
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("處理前的名稱:" + filename); ServletContext sc = this.getServletContext(); sc.setAttribute("name", "太谷餅"); }
然後再servletDemo2中獲取該servletcontext物件
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = request.getSession().getServletContext(); String a = (String)sc.getAttribute("name"); response.getWriter().write(a); }
在瀏覽器中訪問該地址:http://localhost/app/servlet/servletDemo2
獲取資原始檔
1.採用ServletContext物件獲取
特徵:必須有web環境,任意檔案,任意路徑。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//拿到全域性物件
ServletContext sc = this.getServletContext();
//獲取p1.properties檔案的路徑
String path = sc.getRealPath("/WEB-INF/classes/p1.properties");
System.out.println("path=" + path);
//建立一個Properties物件
Properties pro = new Properties();
pro.load(new FileReader(path));
System.out.println(pro.get("k"));
}
2.採用resourceBundle獲取
只能拿取properties檔案,非web環境。
//採用resourceBundle拿取資原始檔,獲取p1資原始檔的內容,專門用來獲取.properties檔案
ResourceBundle rb = ResourceBundle.getBundle("p1");
System.out.println(rb.getString("k"));
3.採用類載入器獲取:
任意檔案,任意路徑。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//通過類載入器
//1.通過類名 ServletContext.class.getClassLoader()
//2.通過物件 this.getClass().getClassLoader()
//3.Class.forName() 獲取 Class.forName("ServletContext").getClassLoader
InputStream input = this.getClass().getClassLoader().getResourceAsStream("p1.properties");
//建立Properties物件
Properties pro = new Properties();
try {
pro.load(input);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//拿取檔案資料
System.out.println("class:" + pro.getProperty("k"));
}