(Recovered from my old Blog).
SiteMesh is an open source framework that implements the Decorator pattern. It essentially takes the output stream from a web application, and adds elements to (’decorates’) it. Why would we want that? Put simply, it is an incredibly clean way of adding headers/footers/anything, with the underlying jsp (or whatever) having no knowledge of that fact it will decorated. In combination with Spring MVC, this creates a powerful weapon for your developer arsenal.
This tutorial assumes you have an existing Spring MVC project.
To enable SiteMesh, first either include the jar in your lib folder or add it as a Maven dependency (opensymphony | sitemesh). Next, add the following to your web.xml:
1 2 3 4 5 6 7 8 9 10 11 |
<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> |
Now we create a new file decorators.xml in WEB-INF. This file tells SiteMesh which files to map, and which ‘decorator’ (which we haven’t got to yet) to use. IMPORTANT – in most guides you see, it will tell you to map WEB-INF/jsp or similar. Remember, Spring MVC is handling the jsp references, so you actually want to point at your html folders/files (Spring MVC totally abstracts the jsp file layer).
1 2 3 4 5 6 7 |
<?xml version=“1.0” encoding=“ISO-8859-1”?> <decorators defaultdir=“/WEB-INF/decorators”> <decorator name=“master” page=“master.jsp”> <pattern>/*</pattern> </decorator> </decorators> |
The file master.jsp above is the decorator. Create a file called /WEB-INF/decorators/master.jsp containing the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<%@ taglib prefix=“decorator” uri=“http://www.opensymphony.com/sitemesh/decorator” %> <html> <head> <title> :: nedlowe.co.uk :: <decorator:title /> :: </title> </head> <body> <div id=“header”> <a href=“http://www.nedlowe.co.uk/”>http://www.nedlowe.co.uk/</a> </div> <div id=“main”> <decorator:body /> </div> </body> </html> |
And you’re done! Load any page in your Spring MVC application – and you should see the output has been decorated.
The two decorator tags above look at the pre-decorated page, pull out the respective head and body, and insert them into the output stream. For more complicated usage, see the SiteMesh homepage.
Now let’s look forward to SiteMesh 3!