(一)简介
OS(OpenSymphony)的SiteMesh是一个用来在JSP中实现页面布局和装饰(layout and decoration)的框架组件,
能够帮助网站开发人员较容易实现页面中动态内容和静态装饰外观的分离。
(二)原理
SiteMesh是基于Servlet的filter的,即过滤流。它是通过截取response,并进行装饰后再交付给客户。其中涉及到两个名词: 装饰页面(decorator page)和 "被装饰页面(Content page)" , 即 SiteMesh通过对Content Page的装饰,最终得到页面布局和外观一致的页面,并返回给客户
(三)与freemarker的比较:
用sitemesh 的话。你的某个action生成的页面,只要是局部就可以。比如生成一个数据
显示的table,外面的html, header, footer这些都交给sitemesh 去装饰了;
如果用freemarker的话。你的某个action生成的页面需要关注的是整个html,
只是你把header, footer, sidebar 这些抽取出来了而已
(四)使用步骤: 把握几个要点:jar, 过滤器配置,装饰器描述文件(decorators.xml),模板文件,标签引入, 测试页面
1. 下载并导入jar包:
sitemesh-2.4.2.jar
<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>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<decorators>
<!-- 不需要过滤的请求 -->
<excludes>
<pattern>/static/*</pattern>
<pattern>/remote/*</pattern>
</excludes>
<!-- 定义装饰器要过滤的页面 -->
<decorator name="default" page="/decorators/default.jsp">
<pattern>/*</pattern>
</decorator>
</decorators>
如上,定义了一个叫default的装饰器,对应的模板文件在web-root的decorators目录下,叫做default.jsp、
1)一个decorator 节点定义了一个装饰器,通过pattern指定要拦截的URL
2)excludes节点指定要排除的URL
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="sitemesh"
<%@ taglib uri="
http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>SiteMesh示例主页面-<sitemesh:title /></title>
<sitemesh:head />
</head>
<body>
<%@ include file="header.jsp"%>
<div id="content">
<sitemesh:body />
</div>
<%@ include file="footer.jsp"%>
</body>
</html>
sitemesh中常用的三种标签
<前缀:title>:
插入原始页面(被包装页面)的title标签中的内容,还可以添加一个缺省值
<前缀:head>:
插入原始页面(被包装页面)的head标签中的内容(不包括head标签本身)。
<前缀:body>:插入原始页面(被包装页面)的body标签中的内容
1)webroot中创建一个index页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>sitemesh测试</title>
</head>
<body>
我的第一个JFinal程序
</body>
</html>
2)webroot下的static目录也创建一个index页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>有人拦截我吗?</title>
</head>
<body>
有人拦截我吗?
</body>
</html>
1)访问webroot中的测试页面index.jsp,sitemesh过滤器会为index.jsp自动插入header和footer部分(当然访问其他页面也一样,只要被拦截)
2)访问static下的index.jsp,发现只有Index页面本身的部分,header和footer不会插入,因为在
decorators.xml中被过滤了