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")); }