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

       实际使用中,我们发现在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标签设置动态参数(推荐)

扫描二维码关注公众号,回复: 516908 查看本文章

        <%@ 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;
       }

       

猜你喜欢

转载自1349469499.iteye.com/blog/2272180
今日推荐