您的位置:首页 > 其它

使用SiteMesh装饰页面

2010-03-22 14:41 267 查看
  使用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的知识可参考官方文档和下面这篇文章:http://www.cjsdn.net/post/view?bid=29&id=178862
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息