Introduction

Window toolkits typically provide a layout mechanism that positions widgets in a container; for example, AWT and Swing have layout managers, whereas VisualWorks Smalltalk has wrappers.

Because layout undergoes many changes over the course of development, it's important to encapsulate that functionality so layout can be modified with minimal impact to the rest of the application. In fact, layout managers are an example of one of the tenets of object-oriented design: encapsulate the concept that varies,1 which is also a fundamental theme for many design patterns.

JSP does not provide direct support for encapsulating layout, so web pages with identical formats usually replicate layout code; for example, A Web Page Layout shows a web page containing sections for a header, footer, sidebar, and main content.

 

The layout of the page shown in A Web Page Layout is implemented with HTML table tags, as listed in Including Content.

Including Content

<html><head><title>Templates</title></head>

<body background='graphics/blueAndWhiteBackground.gif'>

 

<table width='610'>

<tr valign='top'><td><jsp:include page='sidebar.jsp'/></td>

<td><table>

<tr><td><jsp:include page='header.html'/></td></tr>

<tr><td><jsp:include page='chapter.jsp'/></td></tr>

<tr><td><jsp:include page='footer.jsp'/></td></tr>

</table>

</td>

</tr>

</table>

</body></html>

In Including Content, content is included with <jsp:include>,2 which allows content to vary without modifying HTML; however, because the layout is hardcoded, layout changes require modifications to the page. If a website has many pages with identical formats, even simple layout changes require modifications to all of the pages.

DISCUSSION

Including Dynamic Content

<html><head><title>Templates</title></head>

<body background='graphics/blueAndWhiteBackground.gif'>

 

<table width='610'>

<tr valign='top'><td><jsp:include page='sidebar.jsp'/></td>

<td><table>

<tr><td><jsp:include page='header.html'/></td></tr>

<tr><td><jsp:include page='chapter.jsp'/></td></tr>

<tr><td><jsp:include page='footer.jsp'/></td></tr>

</table>

</td>

</tr>

</table>

</body></html>

To minimize the impact of layout changes, a mechanism is needed for dynamically including layout in addition to content. That way, both layout and content can be changed without modifying files that use them. For large websites that have many pages with identical formats, such a mechanism is valuable because it localizes changes to layout. That mechanism is JSP templates.