A JSP page can include page fragments from other files to form the complete response. You can use this, for instance, to keep header, footer, and navigation bar content in separate files and include them in all other pages. There are two include mechanisms: the include directive and the include action. It’s not always obvious which one to use, though.
The include directive, <%@ include file="filename.inc" %>, includes the content of the specified file during the translation phase–when the page is converted to a servlet. The main page and the included file are simply merged. This means that scripting variables declared in one file (using scripting elements or an action element like <jsp:useBean>) are visible in all files and must have unique names. Some containers detect changes in files included with the directive, but the specification doesn’t require it. Therefore, changes you make to the included file in a running system may not be reflected immediately; you may have to update the main JSP page, or remove the class file generated for the main page in order to see the change.
The include action, <jsp:include page="pagename.jsp" flush="true" />, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user. As opposed to the include directive, the page name can be specified as a so-called request-time attribute value, so which page to include can be decided when the main page is requested. Since it’s the response generated by the page that is included, not the content of the page itself, scripting variables declared in one file are not available to the other files. To share an object between the pages you must instead place it in one of the following JSP scopes: request, session or application scope. If you change a page included with the include action, the change always takes effect immediately.
My rule of thumb for when to use the different mechanisms is this:
- Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
- Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.
Filed under: JSP | 19 Comments »