您的位置:首页 > Web前端 > JavaScript

jsp及js中获取项目上下文路径

2016-01-20 11:52 846 查看

       实际使用中,我们发现在JSP中的有时用到 "相对路径",但有时可能会出现问题。多次转发之后的相对路径会发生改变,因为它是相对于 "URL请求地址" 寻找的相对路径。

       鉴于上面的情况,总结一下几种方法解决。

 

      1.直接使用绝对路径

     <%

         //项目上下文路径
         String path = request.getContextPath();
         String basePath =                 

         request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 

         //放入pageContext中
         pageContext.setAttribute("basePath",basePath);
     %>

     使用示例:<html><a href="${pageScope.basePath}jsp/index.jsp"></a></html>

 

        2.c标签设置动态参数(推荐)

        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

        <c:set var="basePath"

          value="${pageContext.request.scheme}://${pageContext.request.serverName}:

          ${pageContext.request.serverPort}${pageContext.request.contextPath}" />

        使用示例:<html><a href="${basePath}/jsp/index.jsp"></a></html>

 

        3.js中获取项目上下文路径

        function getContextPath() {
           var contextPath = document.location.pathname;
           var index = contextPath.substr(1).indexOf("/");
           contextPath = contextPath.substr(0, index + 1);
           delete index;
           return contextPath;
       }

 

       

 

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: