分享

request.getContextPath()

 然并卵书屋 2017-07-09

今天终于明白了jsp中的request.getContextPath()是怎么回事了。

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" />

OK!

 

 

 

 

 

 

参考文章:http://www.cnblogs.com/yqskj/articles/2226401.html

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多