SiteMesh 是一个网页布局和修饰的框架,利用它可以将网页的内容和页面结构分离,以达到页面结构共享的目的。
它通过对所有的用户请求进行过滤,并对服务器向客户端响应也进行过滤,从而给原始的服务器响应加入一定的装饰,可以是header、footer等,然后将经过装饰后的页面送回浏览者。对于被装饰的页面而言,它无需知道自身被谁装饰,也无从知道自身被谁装饰。
SiteMesh通过配置文件来配置指定的装饰器,用于过滤某些页面,则该装饰器会装饰这些页面,从而提供更好的页面效果,通过SiteMesh的页面装饰,可以提供更好的代码复用,所有的页面装饰效果耦合在目标页面中,无需使用include指令来显式包含装饰效果,目标页面与装饰页面完全分开。提供更好的解耦,而且可以在应用中所有的页面都使用相同的装饰页面,整个Web应用会有更统一的风格,会提供更好的整体效果。
SiteMesh通过Filter来截取request和response,然后给原始的页面加入一定的装饰,再把结果返回给客户端。
使用SiteMesh的步骤:
1、maven引入:
<dependency>
<groupId>opensymphony</groupId>
<artifactId>sitemesh</artifactId>
<version>2.4.2</version>
</dependency>
2、在web.xml中增加过滤器:
<!-- Sitemesh -->
<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>
3、在WEB-INF中创建decorators.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/layouts/">
<!-- 不需要过滤的请求 -->
<excludes>
<pattern>/static/*</pattern>
<pattern>/remote/*</pattern>
</excludes>
<!-- 定义装饰器要过滤的页面 -->
<decorator name="default" page="default.jsp">
<pattern>/*</pattern>
</decorator>
</decorators>
1、在decorator标签的page属性是指向的jsp装饰页面,下面拦截的/*是真正的普通页面,要被page指定的页面所修饰,修饰页面就是写了一堆SiteMesh的标签,然后将pattern标签上url拦截到的被装饰页面的对应装饰页面标签的head和body提取过来填充到装饰页面中。
2、excludes标签下配置的是不需要拦截忽略的url。
3、可以不需要使用<pattern>进行拦截被装饰页面,可使用meta进行拦截<meta name="xxx" content="xxx" />
引入了SiteMesh标签:
<sitemesh:title /> 会自动替换为被过滤页面的title。
<sitemesh:head /> 会把被过滤页面head里面的东西(除了title)放到这里。
<sitemesh:body /> 被过滤的页面的body内容会放到这里。