首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Sitemesh 入門教學 (一):Hello World 與裝飾器模式

     編輯:Java 相關知識

什麼是 Sitemesh?

Sitemesh 是 OpenSymphony 開發的 J2EE 框架,採用裝飾器模式,透過 Filter 攔截 Request/Response,將頁面片段(header、content、banner)組合為完整視圖,消除 JSP 中大量 <%@ include %> 的重複程式碼,提升可維護性與複用性。

快速上手:Hello Sitemesh

1. 部署 Filter 與標籤庫 (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>
</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>

2. 放置必要檔案

  • sitemesh.jar → WEB-INF/lib
  • sitemesh-decorator.tld, sitemesh-page.tld → WEB-INF

3. 定義裝飾器映射 (WEB-INF/decorators.xml)

<decorators defaultdir="/_decorators">
  <decorator name="main" page="main.jsp">
    <pattern>*</pattern>
  </decorator>
</decorators>

4. 編寫裝飾器頁面 (_decorators/main.jsp)

<%@ 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>

5. 建立內容頁面 (index.jsp)

<%@ 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>取得原始頁面任意標籤屬性
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved