Sitemesh 是 OpenSymphony 開發的 J2EE 框架,採用裝飾器模式,透過 Filter 攔截 Request/Response,將頁面片段(header、content、banner)組合為完整視圖,消除 JSP 中大量 <%@ include %> 的重複程式碼,提升可維護性與複用性。
<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>
<taglib>
<taglib-uri>sitemesh-decorator</taglib-uri>
<taglib-location>/WEB-INF/sitemesh-decorator.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>sitemesh-page</taglib-uri>
<taglib-location>/WEB-INF/sitemesh-page.tld</taglib-location>
</taglib>
sitemesh.jar → WEB-INF/libsitemesh-decorator.tld, sitemesh-page.tld → WEB-INF<decorators defaultdir="/_decorators">
<decorator name="main" page="main.jsp">
<pattern>*</pattern>
</decorator>
</decorators>
<%@ page contentType="text/html; charset=GBK"%>
<%@ taglib uri="sitemesh-decorator" prefix="decorator" %>
<html>
<head><decorator:title default="Sitemesh 範例"/></head>
<body>
<h1><decorator:title/></h1>
<hr/>
<decorator:body/>
<hr/>
<address>chen56@msn.com</address>
</body>
</html>
<%@ page contentType="text/html; charset=GBK"%>
<html>
<head><title>首頁</title></head>
<body>本頁只有一句,就是本句。</body>
</html>
訪問 index.jsp,Sitemesh Filter 自動套用 main.jsp 裝飾,輸出完整頁面:標題來自內容頁,主體內容被插入裝飾器的 <decorator:body/> 處。所有符合 /* 模式的頁面自動獲得相同版面,無需修改內容頁。
| 標籤 | 用途 |
|---|---|
<decorator:head> | 插入原始頁面 <head> 內容 |
<decorator:body> | 插入原始頁面 <body> 內容 |
<decorator:title> | 插入原始頁面標題,可設 default |
<decorator:getProperty> | 取得原始頁面任意標籤屬性 |