1. 程式人生 > >javaWeb中getContextPath()等方法獲取路徑的區別

javaWeb中getContextPath()等方法獲取路徑的區別

因為自己在學習的過程中也經常弄混,被坑...故測試並分享

其實仔細 想想 結果和函式名稱 還是很有聯絡的。不難分清。微笑

假定你的Webapp名稱為Jianzhan-3,你在瀏覽器中輸入請求路徑: 

http://localhost:8080/Jianzhan-3/testPath

測試結果如下:

注意:

---------------------------------------------------------------------------

 request.getRealPath("") 這個方法已經不推薦使用

替換方法

request.getSession().getServletContext().getRealPath() 得到站點的絕對地址
request.getSession().getServletContext().getRealPath(File.separator) 得到專案的絕對路徑

在Servlet 裡用this.getServletContext().getRealPath("/");獲得絕對路徑。

在struts 裡用this.getServlet().getServletContext().getRealPath("/");獲得絕對路徑。