<%=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.jsp3、 System.out.println(request.getRequestURI());
打印結果:/news/main/list.jsp4、 System.out.println(request.getRealPath("/"));
打印結果:F:/Tomcat 6.0/webapps/news/test
參考文章:http://www.cnblogs.com/yqskj/articles/2226401.html
Request.getContextPath() 返回站點的根目錄
request.getRealpath("/")得到的是實際的物理路徑,也就是你的項目所在服務器中的路徑
request.getScheme() 等到的是協議名稱,默認是http
request.getServerName() 得到的是在服務器的配置文件中配置的服務器名稱 比如:localhost .baidu.com 等等
request.getServerPort() 得到的是服務器的配置文件中配置的端口號 比如 8080等等
有一個例子來說明吧
有個web應用程序 名稱就是demo
<% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; String filePath=path+"resources/"; session.setAttribute("path", path); session.setAttribute("basePath", basePath); session.setAttribute("filePath", filePath);%>
以上這段代碼是 demo中每一個jsp頁面中都包含的一段代碼
其中 request.getContextPath() = /demo
basePath = http://localhost:8080
path = http://localhost:8080/demo/
filePath = http://localhost:8080/demo/resources/
用法:
如果在jsp界面中引用resources/images/文件夾下面的圖片icon.png寫法如下:
<img src="${filePath }images/icon.png" />或者
<img src="${path}resources/images/icon.png" />
同理 如果在resources/CSS/文件夾下引用style.css寫法如下:
<link href="${filePath} css/style.css" rel="stylesheet" type="text/css" />
<link href="${path} resources/css/style.css" rel="stylesheet" type="text/css" />
參考鏈接:http://www.cnblogs.com/yuan1225/p/3219629.html
新聞熱點
疑難解答