SiteMesh框架是OpenSymphony團隊開發的一個非常優秀的頁面裝飾器框架,它通過對用戶請求進行過濾,并對服務器向客戶端響應也進行過濾,然后給原始頁面加入一定的裝飾(header,footer等),然后把結果返回給客戶端。通過SiteMesh的頁面裝飾,可以提供更好的代碼復用,所有的頁面裝飾效果耦合在目標頁面中,無需再使用include指令來包含裝飾效果,目標頁與裝飾頁完全分離,如果所有頁面使用相同的裝飾器,可以是整個Web應用具有統一的風格。
SiteMesh使用很簡單,具體有以下幾步:
1) 拷貝 sitemesh-2.3.jar 到 [web-app]/WEB-INF/lib.
2) 在[web-app]/WEB-INF/新建一個decorators.xml文件,包含以下內容
<decorators>
</decorators>
3)可選項,在[web-app]/WEB-INF/建立一個sitemesh.xml文件,內容如下:
<sitemesh>
<property name="decorators-file" value="/WEB-INF/decorators.xml"/>
<excludes file="${decorators-file}"/>
<page-parsers>
<parser default="true" class="com.opensymphony.module.sitemesh.parser.FastPageParser"/>
<parser content-type="text/html" class="com.opensymphony.module.sitemesh.parser.FastPageParser"/>
<parser content-type="text/html;charset=gbk" class="com.opensymphony.module.sitemesh.parser.FastPageParser"/>
</page-parsers>
<decorator-mappers>
<mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
<param name="config" value="${decorators-file}"/>
</mapper>
</decorator-mappers>
</sitemesh>
4)在[web-app]/WEB-INF/web.xml
添加以下內容:
<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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
一個簡單的例子
1)
在[web-app]
下創建一個decorators文件夾,在該文件下再創建一個裝飾頁面main.jsp,內容如下:
<%@ page contentType="text/html; charset=GBK"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
<html>
<head>
<title><decorator:title default="第一個裝飾器頁面"/></title>
<decorator:head/>
</head>
<body>
SiteMesh快速入門<hr>
<decorator:body />
<hr>
<div style="font:9pt" align="center">SiteMesh快速入門</div>
</body>
</html>
2)創建一個目標頁面index.jsp,內容如下:
<%@ page contentType="text/html; charset=GBK"%>
<html>
<head>
<title>第一次使用SiteMesh</title>
</head>
<body>
<h3>使用SiteMesh有什么好處?</h3>
<li>目標頁面和裝飾頁面完全分離</li>
<li>做到真正的頁面復用</li>
<li>更容易實現統一的網站風格</li>
</body>
</html>
3)在decorators.xml中加入以下內容:
<?xml version="1.0" encoding="GBK"?>
<decorators defaultdir="/decorators">
<!-- 此處用來定義不需要過濾的頁面 -->
<exculdes>
</exculdes>
<!-- 用來定義裝飾器要過濾的頁面 -->
<decorator name="main" page="main.jsp">
<pattern>/*</pattern>
</decorator>
</decorators>
4)發布運行,結果如下:

如果想了解更多關于SiteMesh的知識可參考官方文檔和下面這篇文章:http://www.cjsdn.net/post/view?bid=29&id=178862