Reusable template pieces

You have headers on every page on your web site. They’re always the same. You have the same footer on every page as well. How stupid would it be to code in the same header and footer tags into every JSP in your web app?

image with no caption

If you’re thinking like a Java programmer (which of course you are), you know that doing that is about as un-OO as it gets. The thought of all that duplicate code probably makes you feel a little sick. What happens when the site designer makes, oh, a tiny little change to the header or footer?

You have to propagate the change everywhere.

Relax. There’s a mechanism for handling this in a JSP—it’s called include. You write your JSP in the usual way, except that instead of putting the reusable stuff explicitly into the JSP you’re authoring, you instead tell the Container to include the other file into the existing page, at the location you select. It’s kind of like saying:

<html><body>

<!- - insert the header file here - ->

Welcome to our site...

blah blah blah more stuff here...

<!- - insert the footer file here - ->

</body></html>

In this section we’ll look at two different include mechanisms: the include directive and the <jsp:include/> standard action.

Get Head First Servlets and JSP, 2nd Edition now with O’Reilly online learning.

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