今天終于明白了jsp中的request.getContextPath()是怎么回事了。
request.getContextPath() 返回站點(diǎn)的根目錄
request.getRealpath("/")得到的是實(shí)際的物理路徑,也就是你的項(xiàng)目所在服務(wù)器中的路徑
request.getScheme() 等到的是協(xié)議名稱,默認(rèn)是http
request.getServerName() 得到的是在服務(wù)器的配置文件中配置的服務(wù)器名稱 比如:localhost .baidu.com 等等
request.getServerPort() 得到的是服務(wù)器的配置文件中配置的端口號(hào) 比如 8080等等
有一個(gè)例子來(lái)說(shuō)明吧
有個(gè)web應(yīng)用程序 名稱就是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中每一個(gè)jsp頁(yè)面中都包含的一段代碼
其中 request.getContextPath() = /demo
basePath = http://localhost:8080
path = http://localhost:8080/demo/
filePath = http://localhost:8080/demo/resources/
用法:
如果在jsp界面中引用resources/images/文件夾下面的圖片icon.png寫(xiě)法如下:
<img src="${filePath }images/icon.png" />或者
<img src="${path}resources/images/icon.png" />
同理 如果在resources/css/文件夾下引用style.css寫(xiě)法如下:
<link href="${filePath} css/style.css" rel="stylesheet" type="text/css" />
<link href="${path} resources/css/style.css" rel="stylesheet" type="text/css" />
OK!
參考文章:http://www.cnblogs.com/yqskj/articles/2226401.html
聯(lián)系客服