How to include page dynamically in JSP page?

In this example we are going to learn how to use <jsp:include> action. This action can be use to include resource dynamically to our JSP pages. For example the resource can be another JSP page, a servlet or event a static html pages. But to make it enable to be processed as a JSP page, such as accepting parameters, we must use the .jsp as the file extension. If we use other extension such as .jspf, it will processed as a static page.

The other things to note is that using the include action will process the page inclusion at the request time. This is why we can pass parameters to the included page using the <jsp:param>. The value can be read by obtaining the parameter from the request object.

But if we use the include directive the inclusion of the page happen when it translated into a Servlet. See the following example about the include directive: How do I include a page fragment into JSP?

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

<jsp:include page="jspf/footer.jsp">
    <jsp:param name="year" value="2012"/>
</jsp:include>

</body>
</html>

Below is the content of our footer.jsp page. In this page we display the footer information with a parameter read from the request object.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<hr size="1"/>
Copyright © <%= request.getParameter("year") %> Kodejava.org. All rights reserved.