Including Page Fragments

You can use a JSP directive and an action to include page fragments in a JSP page. This is a useful technique when parts of all pages in an application are the same, such as headers, footers, and navigation bars.

The JSP include directive reads the content of the specified page in the translation phase (when the JSP page is converted into a servlet) and merges it with the original page:

<%@ include file="header.html" %>

The file attribute is a relative URL. If it starts with a slash, it’s a context-relative path, interpreted relative to the URI prefix assigned for the application. If it doesn’t start with a slash, it’s a page-relative path, interpreted relative to the path for the page that includes the file.

The included file can contain only static content (such as HTML) or it can be a regular JSP page. Its contents are merged with the page that includes it, and the resulting page is converted into a servlet, as described in Chapter 3. This means that all scripting variables declared in JSP declarations, scriptlets, or actions, such as <jsp:useBean> or custom actions that introduce scripting variables, are shared by the main page and all included pages. If the main page declares a variable and the same name is used to declare another variable in an included page, it will result in a translation phase error, since the combined page cannot be compiled.

What happens when the file you include using the include directive is changed actually isn’t specified ...

Get Java Server Pages now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.