ServletContext對象--三大域對象

Servlet三大域對象的應用 request、session、application(ServletContext)web

ServletContext是一個全局的儲存信息的空間,服務器開始就存在,服務器關閉才釋放。瀏覽器

request,一個用戶可有多個;session,一個用戶一個;而servletContext,全部用戶共用一個。因此,爲了節省空間,提升效率,ServletContext中,要放必須的、重要的、全部用戶須要共享的線程又是安全的一些信息。安全

1.獲取servletcontext對象:服務器

ServletContext sc = null;
        sc = request.getSession().getServletContext();
//或者使用
//ServletContext sc = this.getServletContext(); System.
out.println("sc=" + sc);

2.方法:session

域對象,獲取全局對象中存儲的數據app

全部用戶共用一個this

 servletDemo1spa

    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/servletDemo2code

獲取資源文件

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"));
    }
相關文章
相關標籤/搜索