A partial is a page with a piece of HTML or other code that can be included into other pages. Best examples are header and footer files that are being included into all pages of the website. You may also have complicated logic that you would like to separate or some repetitive code.
JSP doesn’t offer partials as a part of the language, but you can use
include tag or directive for this purpose.
There are two different includes available in JSP, static and dynamic.
Static include uses a JSP directive
include meaning they start with an alpha-sign “@”:
<%@ include file="header.html" %>
This directive includes a file during translation phase and tells the container to merge the content of the file into the current JSP file.
Static include is resolved at compile time. If you want to pass parameters from another request they may not be available yet as they will be first known at execution time.
Static includes are faster as the code is inserted at translation time once and for all.
<head> <title>My title</title> </head>
<!DOCTYPE html> <html lang="en"> <%@ include page="header.jsp" %> <body> ... </body> </html>
Generated HTML result:
<!DOCTYPE html> <html lang="en"> <head> <title>My title</title> </head> <body> ... </body> </html>
In this example we included a static header file into main.jsp. This approach won’t give you dynamic titles, but will work for all static pages.
Dynamic includes are resolved at runtime and you can use them to pass parameters from other requests to your partial pages.
In order to make the partial JSP dynamic we will use the
jsp:include tag and pass some parameters with
Including JSP partials dynamically costs more in terms of performance. Dynamic include will make a request that will execute the partial first and then include the output from the partial in the output of the calling page. Both pages will be executed in their own context.
Example with dynamic parameter variables being passed from parent page to partial:
<head> <title><%= request.getParameter("title") %></title> </head>
<footer> My footer </footer>
<!DOCTYPE html> <html lang="en"> <jsp:include page="header.jsp"> <jsp:param name="title" value="Main title" /> </jsp:include> <body> ... </body> <%@ include page="footer.html" %> </html>
Generated HTML result:
<!DOCTYPE html> <html lang="en"> <head> <title>Main title</title> </head> <body> ... </body> <footer> My footer </footer> </html>
In this example it is more beneficial to include the footer in a static way as there is no need in passing parameters. Static include will execute at compile time inside the context of the calling page and will be reused if more includes are needed.