SiteMesh Tutorial with Examples

09/07/2008

SiteMesh is a web layout framework for Java.  It differs from from frameworks such as Tiles in that it utilizes the decorator pattern.  For example, you create a number of pages and then you tell SiteMesh that you’d like to add the same header, footer, and menus to each of those pages.  This tutorial will give you a simple example of how SiteMesh can be used to give you a cleaner layout architecture and speed development times.

Start by downloading SiteMesh and adding sitemesh-2.3.jar to your WEB-INF/lib directory.  Then add the SiteMesh filter to your web.xml file like so:

<filter>
    <filter-name>sitemesh<filter-name>
    <filter-class>
        com.opensymphony.module.sitemesh.filter.PageFilter
    </filter-class>
<filter>

<filter-mapping>
    <filter-name>sitemesh<filter-name>
    <url-pattern>/*</url-pattern>
<filter-mapping>

This will call the SiteMesh filter whenever a page on your site is accessed.  Now we’ll need to create a /WEB-INF/decorators.xml file:

<decorators defaultdir="/WEB-INF/decorators">
    <decorator name="main" page="main.jsp">
        <pattern>/WEB-INF/pages/*</pattern>
    </decorator>
</decorators>

This will decorate all of the pages located under /WEB-INF/pages/ with the decorator /WEB-INF/decorators/main.jsp, which we’ll create next:

<%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator" %>

<head>
  <title>
    Lumidant.com - <decorator:title default="SiteMesh Tutorial Example" />
  </title>
  <style type="text/css">@import "css/global.css";</style>
  <decorator:head />
  <body>
    <div id="header">
      <h2><a href="http://www.lumidant.com/">Lumidant.com</a> Tutorials</h2>
    </div>
    <div id="content">
      <decorator:body />
    </div>
  </body>
</html>

This decorator does a couple of things.  First off, it create an HTML title tag, which starts as “Lumidant.com – ” and then appends the title of the page that is being decorated.  If that page does not have a title tag, then a default is used to render “Lumidant.com – SiteMesh Tutorial Example”.  It then adds a global style sheet to every page being decorated and appends whatever is in that page’s head tag, which is useful for page-specific JavaScript, etc.  The decorator continues by adding a header to each page reading “Lumidant.com Tutorials” followed by the decorated page’s content.

Pretty cool, right?  If anyone is familiar with a similar decorator framework in PHP, please let me know.