關於Servlet獲取資原始檔的路徑問題
以eclipse中的java web專案為例,properties檔案作為資原始檔
有如下結構的專案,在WebContent、WEB-INF及src下分別有db1.properties,db2.properties,db3.properties三個檔案。
在Servlet中使用ServletContent獲取資原始檔時,常用的方法有:
1.getResourceAsStream(path)
path即資原始檔的路徑寫法:
(1)如果資原始檔放在src下的某個包下面:/WEB-INF/classes/包名/檔名
例獲取如上圖src下的servlet.study包下的db3.properties檔案,寫法:
InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/servlet/study/db3.properties");
(2)如果資原始檔放在WebContent即Web根目錄下面:/檔名(這裡以eclipse中的web專案為例,和WebRoot是一個道理)
例獲取如上圖WebContent下的db1.properties檔案,寫法:
InputStream in=this.getServletContext().getResourceAsStream("/db1.properties");
(3)如果資原始檔放在WEB-INF下面:/WEB-INF/檔名
例獲取如上圖WEB-INF下的db2.properties檔案,寫法:
InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/db2.properties");
2.getRealPath(path)
此方法的path是檔案的絕對路徑
例獲取如上圖src下的servlet.study包下的db3.properties檔案,寫法:
String path=this.getServletContext().getRealPath("/WEB-INF/classes/servlet/study/db3.properties");