標籤:
ServletContext讀取資源檔內容的方式有兩種:
方法1.
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/data.properties");Properties pros = new Properties();pros.load(in);String username = pros.getProperty("username");String password = pros.getProperty("password");System.out.println("username = " + username);System.out.println("password = " + password);}
這裡須要注意的是data.properties檔案的位置在Myeclipse的src檔案夾下,為啥getResourceAsStream方法傳入的參數確實"/WEB-INF/classes/data.properties"
這是由於這些代碼有webserver運行,當項目公布以後。data.properties檔案就會被放到tomcat安裝檔案所在目錄下。
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbTYzMTUyMTM4Mw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" >
所以這裡傳入參數就解釋清楚了。
方法2
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String path = this.getServletContext().getRealPath("/WEB-INF/classes/data.properties");FileInputStream in = new FileInputStream(path);Properties pros = new Properties();pros.load(in);String username = pros.getProperty("username");String password = pros.getProperty("password");System.out.println("username = " + username);System.out.println("password = " + password);}
這裡首先通過getRealPath方法擷取data.properties檔案的絕對路徑,然後通過FileInputStream擷取檔案流。
J2EE之ServletContext讀取資源檔