【问题标题】:Determine filesystem path of current JSP page确定当前 JSP 页面的文件系统路径
【发布时间】:2014-11-04 16:04:58
【问题描述】:

在一个JSP页面里面,我是确定该页面在文件系统上的当前路径,例如:

WEB-INF/jsp/currentPage.jsp

我希望能够 jsp:include 到基于当前文件系统路径的另一个页面,而不是用户用来访问该页面的 URL。

我希望能够将相同的代码复制/粘贴到多个 JSP 并让每个页面都知道其文件系统路径。

【问题讨论】:

  • 这似乎是非常糟糕的做法。不要超出应用范围。

标签: java jsp tomcat


【解决方案1】:

要引用其他 jsp 页面(以及其他 JSP 实用方法),请使用 JSTL 库。非常便利。使用方法可以参考this page。

【讨论】:

    【解决方案2】:

    根据要求使用 geturi 方法:

    String uri = request.getRequestURI();
    String pageName = uri.substring(uri.lastIndexOf("/")+1);
    

    【讨论】:

    • 这将返回root of the servlet的路径,我想要当前JSP页面的路径。我希望能够将相同的代码复制/粘贴到许多 JSP 并让每个页面都知道其文件系统路径。
    • 获取uri并解析它以了解您的jsp页面。
    • 这也不行,因为 JSP 包含在其他 JSP 中。我需要实际的文件系统路径,而不是将其从请求 URI 中提取出来。
    • 那你到底需要什么?您也可以在问题中添加示例吗?
    【解决方案3】:

    答案是here。基本上,您可以在 this.getClass() 上使用正则表达式来确定完整路径。

    在 JSP 中:

    <jsp:include page='<%= SkinController.getSkinPath(this.getClass() ) %>' />
    

    在 SkinController.java 中

    public static String getSkinPath( Class<?> cls ){
        Pattern pattern = Pattern.compile("org.*INF.?.(jsp|tiles).(.*?)_jsp");
    
        String name = cls.getName();
    
        Matcher matcher = pattern.matcher(name);
    
        if( matcher.matches() ){
            String type = matcher.group(1);
            String path = matcher.group(2).replace(".", "/");
    
            //fullPath is the value we're looking for int he original question
            String fullPath = type.concat("/").concat(path).concat(".jsp");
    
            return getSkinPath(fullPath);
        }else{
            return "";
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2014-01-04
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多