1. 程式人生 > >jsp中的request.getContextPath()

jsp中的request.getContextPath()

tex 默認頁 spa ref -c 文件的 ner image text

jsp中的request.getContextPath()

<%=request.getContextPath()%>是為了解決相對路徑的問題,可返回站點的根路徑。

但不用也可以吧,比如<a href="<%=request.getContextPath()%>/catalog.jsp">
我就直接用<a href="catalog.jsp">也行啊,這兩個文件是在同一個目錄下的

比如你要生成一個文件放在服務器上得一個目錄下,你可以使用request.getContextPath()+/dir,組成一個完整得目錄結構!

但在JSP文件裏,通過request.

getContextPath()得到的路徑卻為空,為什麽?

你在context中沒有配置path屬性,所以你的工程文件就是在根目錄下,相當於path="";即是你直接在 瀏覽器中輸入你的服務器ip就會到你的jsp頁面,而不是tomcat的默認頁面;所以你通過request.getContextPath()得到的字 符串是為空的;它是獲得虛目錄的;
如果你想得到工程文件的實際物理路徑,可通過:<%=request.getRealPath("/")%>,這樣頁面就會輸出:d:/web

request.getScheme();
返回的協議名稱,默認是http

request.getServerName()
返回的是你瀏覽器中顯示的主機名,你自己試一下就知道了

getServerPort()
獲取服務器端口號

技術分享


假定你的web application 名稱為news,你在瀏覽器中輸入請求路徑:

http://localhost:8080/news/main/list.jsp

則執行下面向行代碼後打印出如下結果:

1、 System.out.println(request.getContextPath());

打印結果:/news
2、System.out.println(request.getServletPath());

打印結果/main/list.jsp
3、 System.out.println(request.getRequestURI());

打印結果/news/main/list.jsp
4、 System.out.println(request.getRealPath("/"));

打印結果:F:\Tomcat 6.0\webapps\news\test

技術分享 技術分享 技術分享 技術分享 技術分享 技術分享

jsp中的request.getContextPath()