JSP include指令,jsp:include动作,相对路径与绝对路径

时间:2014-02-17 19:44:41

标签: java jsp servlets path jspinclude

我在基于JSP的webapp中做了一些基本的模板。例如,我希望有一个标准的页眉和页脚(基本HTML),我将其插入到每个JSP中。

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

现在,在home.jsp内,我想要提取模板文件。首先,我尝试jsp:include操作:

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

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

对我来说很奇怪,考虑到Eclipse说路径是有效的。

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

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

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

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

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

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

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

3 个答案:

答案 0 :(得分:4)

/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

答案 1 :(得分:0)

回答为什么 - jsp:include是一个运行时指令,不像<%@ include ... %>指令恰好是编译时指令(实际上是转换时间)。

详情请见:JSP Performance using jsp:include

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

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

The Java EE 6 Tutorial - Web Module Structure

答案 2 :(得分:0)

我在这里阅读了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根目录的路径。

相关问题