How do I include a page fragment into JSP?

Date: 2010-09-16. Category: jsp.snippets examples. Hits: 11K time(s).

In this example you can learn how to include a JSP fragment into another JSP page. This is a common practice when creating a web application where we usually have a navigation section, the main content and the footer of a web page.

Using the include directive make it simpler to maintain the fragment of a web page, which mean that when we need to change the footer section we just need to alter the footer include file and all the page that includes it will get the benefit.

The page inclusion that using the include direction will occurs at page translation time, it is when the JSP page is translated into a Servlet by JSP container. We can use any file extension name for the JSP fragment used by the include directive.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Webapp Include Demo</title>
</head>
<body>

<div id="header">
    <%@ include file="/common/header.jspf" %>
</div>

<div id="content">
    <p>Main application content goes here!</p>    
</div>

<div id="footer">
    <%@ include file="/common/footer.jspf" %>
</div>

</body>
</html>