Introduction to SiteMesh
In the past, I used to build my web applications the old-fashioned way: handcrafting assembly, carefully building my raw byte handlers to work with Unicode, counting instructions, and using make files to target different CPUs.
OK, maybe not.
Although I've never actually felt the need to build my web application with assembly (CISC or RISC), I sometimes think my fellow developers are on a quest to make their development processes as painful as possible. In particular, I've seen many developers agonize over the best way to handle basic web application building blocks: things like headers, footers, navigation bars, support for printable pages, light-weight pages for handheld devices, and more. In the end, things like includes and brute-force copy-and-paste win out surprisingly often.
In my experience, I've been able to easily solve these problems cleanly, easily, and elegantly using the open source servlet filter SiteMesh, which is hosted on java.net. Instead of requiring a new templating language, XSLT, or "porting" your pages to a new system, using SiteMesh often allows you to dramatically simplify your pages while still using ordinary HTML, JSP, servlets (including Struts), and other familiar technologies.
How Does It Work?
SiteMesh implements a page filter, taking advantage of one of the lesser-known features of the servlet specification. Let's imagine you have a simple JSP that returns the current date and time. Ordinarily, the request for the page comes in to the application server, the page is rendered, and then the results are returned to the web browser. SiteMesh, as a page filter, takes the page after it is rendered and performs additional processing before returning the document to the web browser. This change is most simply described as the additional step shown between Figure 1 and Figure 2.
Figure 1. Normal Page Rendering
Figure 2. SiteMesh Page Rendering
Let's look at a simple example of this. Consider the following simple JSP:
Hello World! <br />
<%= 1+1 %>
You'll notice that the page has a title and a body (like any ordinary HTML page). You'll notice a tiny bit of JSP code -- this will be rendered just as you would expect. Indeed, you can use any and all features that you would expect, and you link between the various JSP and other resources just as you might expect.
Now, let's look at a simple SiteMesh "decorator" page. Listing 2 shows a JSP page, called by SiteMesh.
<%@ taglib uri="sitemesh-decorator"
My Site - <decorator:title default="Welcome!" />
<h1><decorator:title default="Welcome!" /></h1>
Looking at the decorator, we can see a few interesting things. First, a SiteMesh taglib is introduced in the first line. This taglib includes everything required to work with the original page. You can see that we use two of the SiteMesh declared tags,
<decorator:body>. Not surprisingly, the
<decorator:title> returns the contents of the
<title> tag in the original page, and
<decorator:body> the content. We're making a few fairly radical changes to the page, including repeating the title both in the
HEAD element as well as the
BODY. We're also adding a link to a printable version of the page.
For comparison, Figure 3 shows the rendered original page and Figure 4 the rendered decorated page. Notice the appearance of the title text both in the browser window title bar and in the HTML of the page in the decorated page. You'll also notice that we added a printable page link, as well -- we'll come back to this later.
Figure 3. Original Undecorated Page
Figure 4. Decorated Page
Obviously, this is a much cleaner system for applying traditional header and footer content than using include directives (such as
<jsp:include page="foo.jsp" flush="true" />). It's much more flexible and natural, and encourages JSP pages with no navigation or other presentation data. I have found that a combination of decorators and CSS overrides of standard HTML tags allows me to virtually eliminate formatting information from my JSP pages.
Note that the screenshots, etc. are based on Windows XP Professional, Tomcat 5.0.19, and Java 2 SDK 1.4.2_03. I'm going to assume that you have installed and are able to get Tomcat working. You might have to tweak things slightly, but I've gotten all of this to work fine on Tomcat 4.1 and WebLogic as well, and SiteMesh lists many other supported web application servers.
SiteMesh 2.0.1, the version described in this article, can be downloaded here. There are four files available for download from SiteMesh's java.net project repository. The sitemesh-2.0.1.jar file is just the core JAR file, sitemesh-2.0.1-sources.zip is self-describing, and sitemesh-example.war provides a complex example showing some of SiteMesh's more advanced features.
To keep things simple, we'll start with the sitemesh-blank.war file, building and modifying as we go along. Instead of just dropping the WAR file into our Tomcat webapps directory, we'll crack open the WAR open and drop it in uncompressed, as shown in Figure 5.
Figure 5. SiteMesh Blank WAR Contents
There are a number of files here, so let's take a moment to describe what they do.
First, the WEB-INF/web.xml file, shown in Listing 3, contains directives to install the SiteMesh filter and the taglib libraries. If you're adding SiteMesh to an existing web application, you'll need to add these directives to your WEB-INF/web.xml file.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
<!-- Start of SiteMesh stuff -->
<!-- End of SiteMesh stuff -->
Note: you'll notice that I've flagged the
url-pattern line -- if you are using Tomcat 5 (instead of Tomcat 4) you'll need to change the pattern from the default
* to something like
* pattern is not allowed under the latest servlet specification.
The WEB-INF/decorators.xml file is used to bind a decorator name to a specific JSP decorator file. So, for example, we might bind a decorator named
handheld to the JSP page decorator
<decorator name="main" page="main.jsp">
<decorator name="panel" page="panel.jsp"/>
<decorator name="printable" page="printable.jsp"/>
As we can see in this code listing, we define three decorators, and then bind them to three similarly named JSP pages. We also see that the default decorator,
main.jsp, will be applied for files by default.
By default, SiteMesh will use the following logic to determine what decorator to apply:
This logic is expressed in described in the sitemesh-2.0.1.jar file at \com\opensymphony\module\sitemesh\factor\sitemesh-default.xml. You can override this behavior with a wide variety of built-in mappers for things like language, client operating system, web browser/user agent, etc. by creating a WEB-INF\sitemesh.xml file. You'll find an example of this included in the sitemesh-example.war file.
- Does the page specifically request a decorator using a meta decorator tag?
- Is the page a frame set (if so, don't apply a decorator)?
- Does the page have a
printable=trueparameter> (If so, use the printable decorator.)
- Does the page specifically request a decorator by the decorator file name?
- Does the page match a pattern in the decorators.xml file?
Conceptually, the first rule that evaluates to true determines the decorator that is used. In the example above, when the
printable=true parameter is present, the
printable.jsp decorator (rule #3) is used instead of the
main.jsp (matched in rule #5). In SiteMesh, these rules are described as mappers.
The three files in the decorators directory are the various decorator JSP files, as described by decorators.xml. We saw an example of a simple decorator above, and we'll look at a more sophisticated example later in this article.
This is the main SiteMesh binary, typically installed in the WEB-INF/lib directory. You can find the Javadoc for this library at www.opensymphony.com/sitemesh/api.
SiteMesh uses two tag libraries, but most users will only need the decorator tags (sitemesh-decorator.tld). You can find documentation on these at www.opensymphony.com/sitemesh/tags.html. We've already touched on the main tags, used to retrieve the head, title, and body. We'll look at the remaining tag,
getProperty, in the next section.
One of the more powerful abilities of SiteMesh is to use the ordinary HTML
meta tag (for example,
<meta name="foo" content="bar">) to pass information from the base page to the decorator. For example, let's say that we would like to define the author of an HTML page using a
meta tag, as shown below.
<meta name="author" content="email@example.com">
Hello World! <br />
<%= 1+1 %>
We can make a decorator "smart" enough to know to look for this
meta tag, and if present, generate the appropriate HTML:
<%@ taglib uri="sitemesh-decorator" prefix="decorator" %>
<decorator:usePage id="myPage" />
<title>My Site -
<decorator:title default="Welcome!" />
<h1><decorator:title default="Welcome!" /></h1>
<a href="mailto:<decorator:getProperty property="meta.author"
(<a href="?printable=true">printable version</a>)
You'll notice that we use a default attribute in the
getProperty tag -- if no author is specified, we'll just assume that it was written by the staff. If you decide to use this model for storing page metadata, you'll want to work with your content developers and other team members to determine what tags you want to use and how you'll be using them. At the simple end, you may want to use
meta tags to describe things like the author and page timestamp. At the complex end, you may do things like standardize on an XML file to manage your site navigation and use a
meta tag to pass the page's node to the decorator.
The page that results from applying this decorator to the JSP page above is shown in Figure 6.
meta Tag Displayed
These page attributes are powerful, and you can retrieve many different properties, not just the
meta tags (here's a list of generated page properties). After using SiteMesh for a while, you'll start thinking about HTML and JSP as a mechanism for generating simple markup -- closer to the original intent of HTML -- without having to make a full switch to an XML/XSL or other template engine.
As we've seen, SiteMesh provides for a powerful, easy-to-use, non-intrusive mechanism for applying page templates. It's easy to envision a wide range of possible uses. For example, you might define a decorator that emits extra debugging information about the page, as determined by the browser (this is especially powerful when combined with a web browser that lets you set an arbitrary user-agent). You might define a decorator with a stripped-down XML output, allowing for easier automated testing. You can even use the decorator to grab content from other pages, for example, to simple portal-like capability.
Once you've gotten comfortable with sitemesh-blank.war, I'd suggest looking at sitemesh-example.war for more features and ideas.
Regardless of how you use SiteMesh, I've found that it lets me centralize a tremendous amount of code, moving it out of my presentation layer and into my decorators, without having to learn a new programming language or templating system.
Oh, and as a final note for those of you still interested in building web pages in assembly, check out home.worldonline.dk/viksoe/asmil.htm.
Good luck and happy coding!