JSP中獲得當前應用的相對路徑和絕對路徑

3.1 JSP中獲得當前應用的相對路徑和絕對路徑 
  根目錄所對應的絕對路徑:request.getRequestURI() 
  文件的絕對路徑  :application.getRealPath(request.getRequestURI()); 
  當前web應用的絕對路徑 :application.getRealPath("/"); 
  取得請求文件的上層目錄:new File(application.getRealPath(request.getRequestURI())).getParent() 
  3.2 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() 
  ) 
  4.java 的Class中獲得相對路徑,絕對路徑的方法 
  4.1單獨的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")); 
  } 
  } 
  4.2服務器中的Java類獲得當前路徑(來自網絡) 
  (1).Weblogic 
  WebApplication的系統文件根目錄是你的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://blog.csdn.net/iougames/archive/2009/07/15/4351502.aspx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章