jsp获取绝对路径

在JavaWeb开发中,常使用绝对路径的方式引入javaScript和CSS文件,这样可以避免因为目录变动导致引入文件找不到的情况,常用的做法是:

一、使用${pageContext.request.contextPath}

  代码” ${pageContext.request.contextPath}”的作用是取出部署的应用程序名,这样不管如何部署,所用路径都是正确的。

例如:

<!--使用绝对路径的方式引入CSS文件-->
<link rel="stylesheet" href="${pageContext.request.contextPath}/themes/default/css/ueditor.css" type="text/css"/>
<!--使用绝对路径的方式引入JavaScript脚本-->
<script type="text/javascript" src="${pageContext.request.contextPath}/ueditor1_3_6-gbk-jsp/ueditor.config.js"></script>

二、使用<%=request.getContextPath()%>和使用${pageContext.request.contextPath}达到同样的效果

<script type="text/javascript" src="<%=request.getContextPath()%>/ueditor1_3_6-gbk-jsp/ueditor.all.js"></script>

拓展:如果页面时HTML,如何获取绝对路径?

  ${pageContext.request.contextPath}在HTML中不会产生我们想要的效果,因此我们只能在页面中使用JS的方式获取绝对路径,常用的方法如下:

 function getWebPath() {
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    return (prePath + postPath);
}
原文地址:https://www.cnblogs.com/longqingyang/p/6093463.html