最近项目用到SiteMesh3,研究学习一段时间后决定写篇博文来记录收获。
SiteMesh
介绍
SiteMesh 是一个网页布局和修饰的框架,利用它可以将网页的内容和页面结构分离,以达到页面结构共享的目的。
Sitemesh是由一个基于Web页面布局、装饰以及与现存Web应用整合的框架。它能帮助我们在由大量页面构成的项目中创建一致的页面布局和外观,如一致的导航条,一致的banner,一致的版权,等等。它不仅仅能处理动态的内容,如jsp,php,asp等产生的内容,它也能处理静态的内容,如htm的内容,使得它的内容也符合你的页面结构的要求。甚至于它能将HTML文件象include那样将该文件作为一个面板的形式嵌入到别的文件中去。所有的这些,都是GOF的Decorator模式的最生动的实现。尽管它是由java语言来实现的,但它能与其他Web应用很好地集成。
下图是SiteMesh的结构图
工作原理
SiteMesh是基于Servlet的filter的,即过滤流。它是通过截取response,并进行装饰后再交付给客户。
其中涉及到两个名词: 装饰页面(decorator page)和 被装饰页面(Content page), 即 SiteMesh通过对Content Page的装饰,最终得到页面布局和外观一致的页面,并返回给客户。
运行SiteMesh3至少需要:
- JDK 1.5
- 一个Servlet 2.5兼容容器
- SiteMesh运行时库
配置及使用
下载
wiki上的下载链接为:http://wiki.sitemesh.org/wiki/display/sitemesh3/Home
GitHub上3.0.1版本下载地址为(含demo):https://github.com/sitemesh/sitemesh3/releases/tag/3.0.1
1、添加maven依赖
pom.xml文件添加以下依赖:
<!--sitemesh-->
<dependency>
<groupId>org.sitemesh</groupId>
<artifactId>sitemesh</artifactId>
<version>3.0.1</version>
</dependency>
2、web.xml中添加SiteMesh过滤器
<web-app>
...
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>org.sitemesh.config.ConfigurableSiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3、创建一个“装饰页面”(decorator page)
该装饰页面包含Web应用程序中常见得布局和样式,它是一个包含<title>
,<head>
和<body>
元素的模板。它至少要包含:
<HTML>
<HEAD>
<title> <sitemesh:write property ='title'/> </ title>
<sitemesh:write property ='head'/>
</HEAD>
<BODY>
<sitemesh:write property ='body'/>
</BODY>
</HTML>
标签<sitemesh:write property='...'/>
将会被SiteMesh重写,用来包含从“被装饰页面”(content page)中提取到的值。可以从被装饰页面”(content page)中提取更多的属性,并且可以自定义规则 。
在WEB应用程序中创建/decorator.html,其中包含:
<html>
<head>
<title>SiteMesh example: <sitemesh:write property='title'>Title goes here</sitemesh:write></title>
<style type='text/css'>
body { font-family: arial, sans-serif; background-color: #ffffcc; }
h1, h2, h3, h4 { text-align: center; background-color: #ccffcc; border-top: 1px solid #66ff66; }
.disclaimer { text-align: center; border-top: 1px solid #cccccc; margin-top: 40px; color: #666666; font-size: smaller; }
<