由于最近项目的原因,接触到了sitemesh。
sitemesh是一个用来在jsp中实现页面布局和装饰(layout and decoration)的框架组件,能够帮助网站开发人员较容易实现页面中动态内容和静态装饰外观的分离。提供了一种在网站中更有效的组织页面布局的方式。
sitemesh设计思想是,用户发送request至服务器,服务器根据此request生成动态数据,生成网页,准备返回给客户端。就在返回前,sitemesh进行拦截,对此网页进行解析,将title、body等部分拆解出来,套上模板后,再返回给客户端。由于sitemesh在返回客户端的最后一步工作,此时的网页已经具备了标准的html网页格式,因此sitemesh只需解析标准的html网页,无需考虑各个web应用是应用了jsp、asp,还是velocity技术,相当灵活。
sitemesh使用了decorator的设计模式。
下面我就用一个通俗易懂的例子告诉大家怎么使用它。
这个就是我这个项目的结构,jsp页面都可以随意放只要指明路径就可以了,decorators.xml放在web-inf下面。
首先是decorators.xml的书写:
<?xml version="1.0" encoding="utf-8"?>
<decorators defaultdir="/decorators">
<!-- 用第一套模板 -->
<decorator name="basic-theme" page="basic-theme.jsp">
<pattern>/data/*</pattern>
</decorator>
<!-- 用第二套模板 -->
<decorator name="basic-theme2" page="basic-theme2.jsp">
<pattern>/data2/*</pattern>
<!-- 不做任何装饰 -->
<decorator name="none">
<pattern>/data3/*</pattern>
</decorators>
你可以选择你自己的模板在page里面定义,<pattern>里面的是你要作用的页面的路径。
下面是aa.jsp
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>jsp</title>
</head>
<body>
我爱中国!
</body>
</html>
aa2.jsp
我爱中国2!
aa3.jsp
我爱中国3!
最重要的xml的配置:
加上下面一句
<!-- 过滤作用,使发送给客户端的页面通过decorator装饰再返回 -->
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.sitemesh.webapp.sitemeshfilter</filter-class>
</filter>
<filter-mapping>
<url-pattern>/*</url-pattern>
</filter-mapping>
下面是装饰页面basic-theme.jsp
basic-theme2.jsp
下面来看看效果图:
下面是用了第一个装饰模板的页面图。
下面是用了第二个装饰模板的页面。
下面是没有用装饰模板的页面。
看到这里相信大家应该对sitemesh很期待了吧,赶紧自己去试试吧。这是jar包下载地址。
<a target="_blank" href="http://www.boyunjian.com/do/jarse/gadetail.do?group=opensymphony&artifact=sitemesh&keyword=sitemesh">sitemesh.jar</a>