---
title: "SiteMesh 2学习（1）：入门简介和简单实例 "
author: "flyer2010"
date: "2011-12-07T19:22:06Z"
tags: []
categories: ["开源软件"]
slug: "sitemesh-2-1"
draft: false
lastmod: "2011-12-07T19:22:06Z"
id: 1296596
url: "https://flyer2010.iteye.com/blog/1296596"
---

SiteMesh简介
* 资料参考：
SIteMesh官方地址：http://www.opensymphony.com/sitemesh/
SIteMesh下载地址：http://java.net/downloads/sitemesh/

* SiteMesh是由一个基于Web页面布局、装饰以及与现存Web应用整合的框架。它能帮助我们在由大量页面构成的项目中创建一致的页面布局和外观，如一致的导航条，一致的banner，一致的版权，等等。

* SiteMesh拦截请求不仅能处理动态的内容，如jsp，php，asp等产生的内容，它也能处理静态的内容，如htm的内容，使得它的内容也符合你的页面结构的要求。甚至于它能将HTML文件象include那样将该文件作为一个面板的形式嵌入到别的文件中去。所有的这些，都是GOF的Decorator模式的最生动的实现。

* SiteMesh是由Java 2 with Servlet, JSP and XML等技术来实现的，这使得他能很好地与J2EE应用结合，但它能与其他Web应用很好地集成，例如CGI (Perl/Python/C/C++/etc), PHP, Cold Fusion,等

* SiteMesh是很容易扩展的，并且他的设计方式使得它很容易实现自定义扩展的需求。

SiteMesh原理

SiteMesh框架是OpenSymphony团队开发的一个非常优秀的页面装饰器框架，它通过对用户请求进行过滤，并对服务器向客户端响应也进行过滤，然后给原始页面加入一定的装饰(header,footer等)，然后把结果返回给客户端。通过SiteMesh的页面装饰，可以提供更好的代码复用，所有的页面装饰效果耦合在目标页面中，无需再使用include指令来包含装饰效果，目标页与装饰页完全分离，如果所有页面使用相同的装饰器，可以是整个Web应用具有统一的风格。

图例：2个页面是从不同的系统产生的（一个jsp，一个CGI），两个页面都被解析了并且有一个共同的装饰器产生到最终的页面，以便显示一致的风格。

![](http://dl.iteye.com/upload/attachment/601921/864ee170-c333-38d0-9e54-8284b4d7ca67.jpg)


SiteMesh简单例子
官网demo：http://java.net/downloads/siteme ... /sitemesh-blank.war，下载后直接运行。
手动建立demo步骤：
1.拷贝sitemesh-2.4.2.jar into /WEB-INF/lib.
2.工程下建立/WEB-INF/decorators.xml ，内容如下：
<?xml version="1.0" encoding="utf-8"?>   
<decorators defaultdir="/decorators">      
       <!-- 此处用来定义不需要过滤的页面 -->      
       <excludes>      
       </excludes>      
       <!-- 用来定义装饰器要过滤的页面 -->      
       <decorator name="main" page="main.jsp">         
            <pattern>/*</pattern>      
       </decorator>   
</decorators>

3.建立文件 /WEB-INF/sitemesh.xml ，包含如下内容：
<sitemesh>   
<property name="decorators-file" value="/WEB-INF/decorators.xml" />   
<excludes file="${decorators-file}" />   
<page-parsers>        
<parser content-type="text/html"            class="com.opensymphony.module.sitemesh.parser.HTMLPageParser" />        <parser content-type="text/html;charset=ISO-8859-1"          class="com.opensymphony.module.sitemesh.parser.HTMLPageParser" />   
</page-parsers>   
<decorator-mappers>        
<mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">         
  <param name="config" value="${decorators-file}" />      
  </mapper>   
</decorator-mappers>
</sitemesh>
4.修改/WEB-INF/web.xml ，在 <web-app>标签内增加如下内容：
<filter>   
<filter-name>sitemesh</filter-name>   
<filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
</filter>
<filter-mapping>   
<filter-name>sitemesh</filter-name>   
<url-pattern>/*</url-pattern>
</filter-mapping>
到此，你的工程已经建立配置好了sitemesh，你现在可以建立装饰器应用到你的web应用了。

二、
装饰器是值那些装饰原始的请求页面。大部分的装饰器包括：
meta tags (keywords, description, author) ：meta标签
stylesheet (CSS) 样式
header 头部
navigation 导航
footer 底部
copyright notice 版权信息