標籤:程式 home bin print style one port gic main
一、JSP中獲得當前應用的相對路徑和絕對路徑
根目錄所對應的絕對路徑 : request.getRequestURI()
檔案的絕對路徑 : application.getRealPath(request.getRequestURI());
當前web應用的絕對路徑 : application.getRealPath("/");
取得請求檔案的上層目錄 : new File(application.getRealPath(request.getRequestURI())).getParent()二、Servlet中獲得當前應用的相對路徑和絕對路徑
根目錄所對應的絕對路徑 : request.getServletPath();
檔案的絕對路徑 : request.getSession().getServletContext().getRealPath(request.getRequestURI())
當前web應用的絕對路徑 :servletConfig.getServletContext().getRealPath("/");
(ServletContext對象獲得幾種方式:
Javax.servlet.http.HttpSession.getServletContext()
Javax.servlet.jsp.PageContext.getServletContext()
Javax.servlet.ServletConfig.getServletContext()
)三、Java 的Class中獲得相對路徑,絕對路徑的方法
單獨的Java類中獲得絕對路徑
根據Java.io.File的Doc文擋,可知: 預設情況下new File("/")代表的目錄為:System.getProperty("user.dir")。
一下程式獲得執行類的當前路徑
package org.cheng.file;
import Java.io.File;public class FileTest {
public static void main(String[] args) throws Exception { System.out.println(Thread.currentThread().getContextClassLoader().getResource("")); System.out.println(FileTest.class.getClassLoader().getResource("")); System.out.println(ClassLoader.getSystemResource(""));
System.out.println(FileTest.class.getResource(""));
System.out.println(FileTest.class.getResource("/")); //Class檔案所在路徑
System.out.println(new File("/").getAbsolutePath());
System.out.println(System.getProperty("user.dir"));
}
} 伺服器中的Java類獲得當前路徑(來自網路)
(1).WeblogicWebApplication的系統檔案根目錄是你的weblogic安裝所在根目錄。
例如:如果你的weblogic安裝在c:\bea\weblogic700.....
那麼,你的檔案根路徑就是c:\.
所以,有兩種方式能夠讓你訪問你的伺服器端的檔案:
a.使用絕對路徑:
比如將你的參數檔案放在c:\yourconfig\yourconf.properties,
直接使用 new FileInputStream("yourconfig/yourconf.properties");
b.使用相對路徑:
相對路徑的根目錄就是你的webapplication的根路徑,即WEB-INF的上一級目錄,將你的參數檔案放在yourwebapp\yourconfig\yourconf.properties,
這樣使用:
new FileInputStream("./yourconfig/yourconf.properties");
這兩種方式均可,自己選擇。(2).Tomcat在類中輸出System.getProperty("user.dir");顯示的是%Tomcat_Home%/bin(3).Resin不是你的JSP放的相對路徑,是JSP引擎執行這個JSP編譯成SERVLET
的路徑為根.比如用建立檔案法測試File f = new File("a.htm");
這個a.htm在resin的安裝目錄下(4).如何讀相對路徑哪?在Java檔案中getResource或getResourceAsStream均可例:getClass().getResourceAsStream(filePath);//filePath可以是"/filename",這裡的/代表web發布根路徑下WEB-INF/classes預設使用該方法的路徑是:WEB-INF/classes。已經在Tomcat中測試。
之前所寫,遷移至此
原文連結:http://user.qzone.qq.com/372806800/blog/1336198862
JSP在項目中的路徑問題