Java JSP include指令、JSP:include操作、相对路径与绝对路径

Java JSP include指令、JSP:include操作、相对路径与绝对路径,java,jsp,servlets,path,jspinclude,Java,Jsp,Servlets,Path,Jspinclude,我正在基于JSP的webapp中进行一些基本的模板制作。例如,我希望有一个标准的页眉和页脚(基本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

我正在基于JSP的webapp中进行一些基本的模板制作。例如,我希望有一个标准的页眉和页脚(基本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>
这工作得很好,拉在我的页脚HTML

但是为什么
jsp:include
不起作用呢?经过一些实验后,我发现将绝对路径放进去确实能让它工作:

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

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


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

/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

为什么?
jsp:include
是一个运行时指令,而
指令恰好是一个编译时指令(实际上是翻译时)

有关更多信息,请参见:

底线-指令以不同的文件夹为基础运行

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


我阅读了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”)
为空


假设上下文相对路径是来自WAR根目录的路径。

您可能需要启动。另一个路径是绝对路径,与应用程序上下文URL有关。它是绝对相对于应用程序上下文的,因此根本不是绝对路径。术语上存在着明显的混乱。当然,你的相对路径必须是完整的,否则,它们将如何工作?这就是我所说的。我并不否认他们毕竟是亲戚。这很有帮助,谢谢。然而,根据您的建议,将JSP放在WEB-INF文件夹之外,可能我没有看到,但我在该链接中看不到推荐的内容。为了支持将JSP放在WEB-INF中,我们有这样一种方法:将JSP文件放在
/WEB-INF/
下是一种常见的做法,它“隐藏”直接请求的页面,允许您确保所有请求都被定向,例如通过控制器或其他机制来保护脚本不被随意浏览。
 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.