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 used 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 be processed as a static page.

The other things to note is that using the <jsp: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 or using expression language variable param.

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" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Include Demo</title>
</head>
<body>

Lorem Ipsum

<jsp:include page="jspf/footer.jsp">
    <jsp:param name="year" value="2021"/>
</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" %>
<hr/>
Copyright © ${param["year"]} Kodejava.org. All rights reserved.

This example will give you the following result in the browser:

JSP Include Action Demo

JSP Include Action Demo

Wayan

2 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.