Jsp – How to include a jsp file located “above” the public_html folder

includejsp

First, I'm from a PHP background (which may be evident by this question). This is such a simple task to accomplish in PHP yet I'm absolutely perplexed on how to accomplish this with jsp.

This is my folder structure on the server:

/home +
      |
      +-/user-+
            |
            +-/includes+
            |          |
            |          +/footer.jsp
            |
            +-/public_html+
                          |
                          +/index.jsp

public_html is the directory being served by Apache Tomcat. So if someone surfs to my domain (sampledomain.com) they see index.jsp

I don't want the "footer.jsp" to be accessible directly via the web. So, it is located in the includes directory which is located one directory above "index.jsp" There is no possible URL that you can type in a browser to reach footer.jsp directly.

Here is the content of footer.jsp

<div id="footer">
    <p>This is a footer</p>
</div>

Here is the content of index.jsp

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <meta charset="UTF-8" />
</head>
<body>
    <h1>Hello World</h1>
    <%@ include file="../includes/footer.jsp" %>
</body>
</html>

I get a tomcat error saying that the file "/../includes.footer.jsp" cannot be found. How do I include a file that is outside of the web page's public_html directory.

In php, I'd just do

<?php include("../includes/footer.php") ?>

Best Answer

As to the cause of the problem, anything outside the web content root is not part of the JSP/Servlet web application's context and should not be seen as such. You need to keep your web files inside the web content root. It's quite possible that multiple (and independent) JSP/Servlet web applications runs together in the webapp's parent folder. If whatever you tried was possible it would have been an integrity leak.

As to the functional requirement:

I don't want the "footer.jsp" to be accessible directly via the web.

The /WEB-INF folder serves this purpose. Drop the file in there.

/home/user/ 
/home/user/public_html/index.jsp
/home/user/public_html/WEB-INF/includes/footer.jsp

And fix the @include accordingly:

<%@ include file="/WEB-INF/includes/footer.jsp" %>

Last but not least, please don't compare PHP with JSP. The PHP culture is littered with many holes and poor practices. JSP actually also (as in using scriptlets :/), but not that much.