【java】web項目中各種路徑的擷取

來源:互聯網
上載者:User

以工程名為/DemoWeb為例:
訪問的jsp為:http://localhost:8080/DemoWeb/test/index.jsp

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

(1)得到工程名:request.getContextPath()

結果:/DemoWeb

(2)得到包含工程名的當前頁面全路徑:request.getRequestURI()

結果:/DemoWeb/test/testpath.jsp

(3)得到IE地址欄地址:request.getRequestURL()

結果:http://localhost:8080/DemoWeb/test/testpath.jsp

(4)得到當前頁面所在目錄下全名稱:request.getServletPath()

結果:/test/testpath.jsp

(5)得到頁面所在伺服器的全路徑(實際的路徑):application.getRealPath("testpath.jsp")

結果:D:\Develop Files\apache-tomcat-5.5.15\apache-tomcat-5.5.15\webapps\DemoWeb\testpath.jsp

D:\Develop Files\apache-tomcat-5.5.15\apache-tomcat-5.5.15為tomcat的安裝路徑

2.java 的Class中獲得相對路徑,絕對路徑的方法

(1)類的絕對路徑:

System.out.println(TestPath.class.getResource("/").getPath());

結果:/E:/workspace/workspace_tcc/DemoWeb/WebRoot/WEB-INF/classes/

System.out.println(TestPath.class.getResource(""));

結果:file:/E:/workspace/workspace_tcc/DemoWeb/WebRoot/WEB-INF/classes/demo1/

(2)得到工程的路徑:System.getProperty("user.dir")

結果:E:\workspace\workspace_tcc\DemoWeb

以下是有關java路徑的連結

Java路徑問題總結

Java相對路徑/絕對路徑總結(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.