使用SiteMesh裝飾頁面

  使用SiteMesh裝飾頁面

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修飾圖


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

發佈了38 篇原創文章 · 獲贊 6 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章