【问题标题】:JSP include directive, jsp:include action, relative vs. absolute pathsJSP 包含指令、jsp:include 操作、相对路径与绝对路径
【发布时间】:2014-03-17 06:33:29
【问题描述】:

我正在我的基于 JSP 的 web 应用程序中做一些基本的模板。例如,我希望有一个标准的页眉和页脚(基本 HTML),我将其拉入到我的每个 JSP 中。

我的内容 JSP 位于 /WEB-INF/jsp/home.jsp,而我的模板 JSP 位于 /WEB-INF/jsp/template/,例如 /WEB-INF/jsp/template/Body-Footer.jsp

所以现在,在home.jsp 中,我想提取我的模板文件。首先,我尝试jsp:include 操作:

<jsp:include page="template/Body-Footer.jsp"></jsp:include>

它会生成错误javax.servlet.ServletException: File &amp;quot;/template/Body-Footer.jsp&amp;quot; not found

我觉得奇怪,考虑到 Eclipse 说路径是有效的。

好的,那么我切换到包含指令:

<%@ include file="template/Body-Footer.jsp" %>

这很好用,拉入我的页脚 HTML。

但是为什么jsp:include 不起作用?经过一些实验,我发现放入绝对路径确实可以工作:

<jsp:include page="/WEB-INF/jsp/template/Body-Footer.jsp"></jsp:include>

现在它工作正常,没有错误。

所以这是我的问题:为什么?为什么我(显然)需要在 jsp:include 操作中使用绝对路径,而不是在 include 指令中?

【问题讨论】:

  • 你可能想开始here

标签: java jsp servlets path jspinclude


【解决方案1】:

我在这里阅读了 JSP 2.0 规范:

 Relative URL Specifications

 * A context-relative path is a path that starts with a slash (/).
 It is to be interpreted as relative to the application to which
 the JSP page or tag file belongs. That is, its ServletContext
 object provides the base context URL.

 * A page relative path is a path that does not start with a
 slash (/). It is to be in- terpreted as relative to the current
 JSP page, or the current JSP file or tag file, depending on where
 the path is being used.

出于安全原因,目前javax.servlet.ServletContext.getRealPath("/WEB-INF/test/test.jsp") 为空。

假设 context-relative path 是来自您的 WAR 根目录的路径。

【讨论】:

    【解决方案2】:

    为什么回答 - jsp:include 是运行时指令,与 &lt;%@ include ... %&gt; 指令不同,后者恰好是编译时指令(实际上是翻译时间)。

    查看更多信息:JSP Performance using jsp:include

    底线 - 指令针对不同的文件夹作为基础运行。

    顺便说一句。 JSP 页面应该在 WEB-INF 文件夹之外,如果你想遵循官方的建议:

    The Java EE 6 Tutorial - Web Module Structure

    【讨论】:

    • 这很有帮助,谢谢。但是,根据您将 JSP 放在 WEB-INF 文件夹之外的建议,也许我错过了它,但我在该链接中看不到推荐的内容。为了支持将 JSP 放入 WEB-INF,我们有这个:stackoverflow.com/questions/6825907/why-put-jsp-in-web-inf
    • 将 JSP 文件放在/WEB-INF/ 下是一种常见的做法,它可以“隐藏”直接请求中的页面,从而确保所有请求都是定向的,例如通过控制器或其他机制保护您的脚本免受随意浏览。
    【解决方案3】:

    /WEB-INF/jsp/template/Body-Footer.jsp 不是绝对路径。它也是一个相对路径。问题是template/Body-Footer.jsp 是一个不完整的相对路径,而另一个是完整的。也就是说,路径是相对于您的应用程序路径的。由于/WEB-INF/ 在您的应用程序路径下,因此您必须包含它。绝对路径意味着像C:/program files/tomcat/webapps/yourapp/WEB-INF/jsp/template/Body-Footer.jsp

    【讨论】:

    • 另一个路径是关于应用程序上下文 URL 的绝对路径。
    • 它与应用程序上下文绝对相对,因此根本不是绝对的。在术语上存在明显的混淆。当然,您的相对路径必须是完整的,否则它们将如何工作?
    • 这就是我所说的。我不否认它们毕竟是亲戚路径。
    猜你喜欢
    • 2012-01-11
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    相关资源
    最近更新 更多