三種載入方式

來源:互聯網
上載者:User

標籤:style   使用   檔案   sp   on   c   ad   new   size   

重點總結:
    即:三種載入方式
    1》傳統載入方式------預設路徑:tomcat/bin/目錄
    2》使用ServletContext對象-----預設路徑:web應用(工程)目錄
    3》使用類載入器------預設路徑:WEB-INF/classes/目錄

 

一、利用ServletContext對象讀取資源檔--預設目錄為:工程(應用)路徑
                重點方法:
                        InputStream getResourceAsStream("檔案路徑");
                code:
                    ServletContext context = this.getServletContext();
                    InputStream is = context.getResourceAsStream("/doc/config.properties");// /代表的當前應用(工程)
                    Properties props = new Properties();
                    props.load(is);
                    System.out.println(props.getProperty("email"));
                    
                注意:
                        1》用傳統方式讀取檔案的時候,是以相對於tomcat\bin的目錄下訪問的
                        2》如果以ServletContext方式讀取資源檔(text/xml/properties),是相對於web伺服器的當前web應用(工程)目錄而言的
                                此時/:表示當前web應用(工程),即:day06
  二、通過類載入器負載檔案:預設目錄為WEB-INF/classes/
                注意:
                    1》類載入器只能載入IDE工具下src目錄下的資源檔,其它目錄無法載入。            
                    2》預設的路徑為WEB-INF/classes/目錄,即:此時/表示:/WEB-INF/classess/目錄
                重點方法:
                    1》獲得類載入器(    Class對象的方法)
                        ClassLoader getClassLoader();
                    2》擷取資源輸入資料流
                        ClassLoader getResourceAsStream(String name);
                步驟:
                    1》取得當前對象的位元組碼對象
                        Class clazz = this.getClass();
                    2》取得當前對象的類載入器
                        ClassLoader cl = clazz.getClassLoader();
                    3》通過類載入器載入資源
                        InputStream is = cl.getResourceAsStream("資源路徑");
                code:
                        //1,擷取當前對象的位元組碼對象
                        Class clazz = this.getClass();
                        //2,返回當前對象的類載入器
                        ClassLoader cl = clazz.getClassLoader();
                        //3,根據類載入器擷取輸入資料流
                        InputStream is = cl.getResourceAsStream("/cn/itcast/web/Servlet/config.properties");

 

三種載入方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.