使用SiteMesh装饰页面

Posted on 2008-03-18 16:08 flustar 阅读(2082) 评论(0)  编辑  收藏 所属分类: 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


只有注册用户登录后才能发表评论。


网站导航:
 

posts - 146, comments - 143, trackbacks - 0, articles - 0

Copyright © flustar