JSP获取绝对路径

来源:互联网 发布:extjs4 获取grid数据 编辑:程序博客网 时间:2024/05/24 04:20
1)采用绝对路径,但为了解决不同部署方式的差别,在所有非struts标签的路径前加${pageContext.request.contextPath},如原路径为: ”/images/title.gif”,改为 “${pageContext.request.contextPath}/images/title.gif”。 代码” ${pageContext.request.contextPath}”的作用是取出部署的应用程序名,这样不管如何部署,所用路径都是正确的。
在JavaWeb开发中,常使用绝对路径的方式来引入JavaScript和CSS文件,这样可以避免因为目录变动导致引入文件找不到的情况,常用的做法如下: ${pageContext.request.contextPath}  等价于  <%=request.getContextPath()%>   或者可以说是<%=request.getContextPath()%>的EL版 意思就是取出部署的应用程序名或者是当前的项目名称。比如我的项目名称是 myBlog 在浏览器中输入为 http://localhost:8080/myBlog/login.jsp 那么,${pageContext.request.contextPath}  或  <%=request.getContextPath()%>  取出来的就是/myBlog,而 "/" 代表的含义就是http://localhost:8080,所以我们项目中应该这样写  ${pageContext.request.contextPath}/login.jsp 缺点:  操作不便,其他工具无法正确解释${pageContext.request.contextPath}  2) 采用相对路径,在每个JSP文件中加入base标签,如:  <base href="http://${header['host']}${pageContext.request.contextPath}/pages/cust/relation.jsp" />  这样所有的路径都可以使用相对路径。
使用${pageContext.request.contextPath}
<pre code_snippet_id="2429525" snippet_file_name="blog_20170601_1_308564" name="code" class="java">&lt;!--使用绝对路径的方式引入CSS文件--&gt; &lt;link rel="stylesheet" href="${pageContext.request.contextPath}/themes/default/css/ueditor.css" type="text/css"/&gt; &lt;!--使用绝对路径的方式引入JavaScript脚本--&gt; &lt;script type="text/javascript" src="${pageContext.request.contextPath}/ueditor1_3_6-gbk- jsp/ueditor.config.js"&gt;&lt;/script&gt;</pre>
使用<%=request.getContextPath()%>和使用${pageContext.request.contextPath}达到同样的效果
<pre code_snippet_id="2429525" snippet_file_name="blog_20170601_2_9850432" name="code" class="java">&lt;script type="text/javascript" src="&lt;%=request.getContextPath()%&gt;/ueditor1_3_6-gbk-jsp/ueditor.all.js"&gt;&lt;/script&gt; </pre>
原创粉丝点击