posts - 66, comments - 12, trackbacks - 0, articles - 0

SiteMesh页面布局组件 转载

Posted on 2010-05-18 15:05 cyantide 阅读(268) 评论(0)  编辑  收藏 所属分类: web
SiteMesh是一个用来在JSP中实现页面布局和装饰(layout and decoration)的框架组件,能够帮助网站开发人员较容易实现页面中动态内容和静态装饰外观的分离。提供了一种在网站中更有效的组织页面布局的方式。

     SiteMesh设计思想是,用户发送request至服务器,服务器根据此request生成动态数据,生成网页,准备返回给客户端。就在返回前,SiteMesh进行拦截,对此网页进行解析,将titlebody等部分拆解出来,套上模板后,再返回给客户端。由于SiteMesh在返回客户端的最后一步工作,此时的网页已经具备了标准的html网页格式,因此SiteMesh只需解析标准的html网页,无需考虑各个Web应用是应用了JSPASP,还是Velocity技术,相当灵活。

     SiteMesh使用了Decorator的设计模式。

 

本文为大家展示一个简单的SiteMesh例子。

     首先创建一个web工程.名字就叫做SitemeshSample.sitemesh-2.3.jar, commons-collections.jar放到lib目录下。

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>

    这里定义了一个过滤器.所有的请求都交由sitemesh来处理

 

     WEB-INF下创建一个decorators.xml文件,内容如下:

    <?xml version="1.0" encoding="UTF-8"?>

    <decorators defaultdir="/decorators">

        <decorator name="main" page="main.jsp">

           <pattern>/*</pattern>

        </decorator>

    </decorators>

    这是定义了模板页,也就是所有页面在返回给客户端之前,先在这里加上装饰,套上模板。

defaultdir="/decorators"说明了模板页的路径。<decorator name="main" page="main.jsp">模板页的名称。    <pattern>/*</pattern>表示对所有的response进行处理

 

    web下面建一个文件夹取名decorators.decoratots下面创建上面定义的模板页面main.jsp,内容如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

       <title><decorator:title />

       </title>

    <body>

       <p>Add head decorator...</p>

       <decorator:body />

       <p>Add foot decorator...</p>

    </body>

</html>

说明:

<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>

此处为decorator标签的声明。因为我们下面要使用到它

<decorator:title />

把请求的原始页面的title内容插入到<title></title>,比如我们要请求index.jsp页面的时候。会把index.jsp中的title的内容放入到这里

<decorator:body />

把请求的原始页面的body内容插入到<body></body>,发现没有我们在这句的前面加上了<p>Add head decorator...</p><p>Add foot decorator...</p>

相当于给我们请求的页面的body内容加上了头部和尾部.实现了模板功能。

 

WEB-INF下创建我们要请求访问的页面index.jsp,内容如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

       <title>SiteMesh Sample Site</title>

    </head>

 

    <body>

       Welcome to the SiteMesh sample...

    </body>

</html>

web工程部署到tomcat容器中。

输入http://localhost:8080/SitemeshSample/index.jsp

 

页面效果如下:

Add head decorator...

Welcome to the SiteMesh sample...

Add foot decorator...

不难发现,我们index.jsp中只有Welcome to the SiteMesh sample... 一句。但是在返回给我们之前套上了main.jsp模板页。在它的前面和后面分别加上了一句话。通过Sitemesh我们可以很容易实现页面中动态内容和静态装饰外观的分离。

 


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


网站导航: