有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JSP包含指令、JSP:include操作、相对路径与绝对路径

我正在基于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>

它生成错误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) 个答案

  1. # 1 楼答案

    解释原因jsp:include是一个运行时指令,而<%@ include ... %>指令恰好是一个编译时指令(实际上是翻译时)

    更多信息请参见:JSP Performance using jsp:include

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

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

    The Java EE 6 Tutorial - Web Module Structure

  2. # 2 楼答案

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

    假设上下文相对路径是来自战争根源的路径

  3. # 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