JSP--整合SiteMesh01

来源:互联网 发布:mac 无线网卡 编辑:程序博客网 时间:2024/06/10 03:34

SiteMesh是一个页面装饰布局框架,在web.xml中添加一个拦截器,来达到页面装饰作用。
1 简单的Demp,非官网的例子,后面会有官网的Demo.
下载sitemesh-2.4.2.jar架包,添加到bin下即可。
在web.xml中添加一个拦截器:

<!-- sitemesh -->    <filter>         <filter-name>sitemesh3</filter-name>         <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>     </filter>     <filter-mapping>         <filter-name>sitemesh3</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping> 

这里配置的是该拦截器对所有的请求都起作用。
在web.xml同一级创建decorators.xml文件,

<?xml version="1.0" encoding="utf-8"?><decorators defaultdir="/WEB-INF/layouts/">    <!-- 此处用来定义不需要过滤的页面 -->    <excludes>        <pattern>/static/*</pattern>    </excludes>    <!-- 用来定义装饰器要过滤的页面 -->    <decorator name="default" page="/view/default.jsp">        <!-- 表示要装饰的是页面匹配符 "/*"-->        <pattern>/view/*</pattern>    </decorator></decorators>

配置static下的文件不需要装饰,而view下的文件需要使用/view/default.jsp文件来配置。
default中通过标签来具体配置页面的是如何来布局的。

<!-- 将头部与被修饰的页面整合在一起 --><body>    <!-- 引入头部信息 -->    <%@ include file="/view/header.jsp"%>    <!-- 引入被装饰的JSP中的body,还可在合适的位置引入相应的信息,如下:    <sitemesh:head/><sitemesh:title/>-->    <sitemesh:body />    <!-- 引入尾部信息 -->    <%@ include file="/view/footer.jsp"%></body>

头的JSP文件:

<?xml version="1.0" encoding="utf-8"?><!-- 模拟页面的头部 --><body>    head.jsp    <br></body>

尾的JSP文件:

<?xml version="1.0" encoding="utf-8"?><!-- 模拟页面的尾部 --><body>    foot.jsp    <br></body>

添加俩个jsp文件访问来测试,文件结构如下:
这里写图片描述
在sitemesh配置文件中配置。当访问static下的jsp文件时是不需要修饰的,访问/view下的文件时通过指定修饰文件来布局。测试如下:
访问/view下的文件
这里写图片描述
访问/static下的文件:
这里写图片描述

2 SiteMesh3官网中的一个例子,具体可参考官网:
下载sitemesh-3.0-alpha-2.jar,添加到lib中。
在web.xml中添加拦截器:

<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>

创建sitemesh3.xml文件,配置哪些路径指定哪些文件来配置:

<xml-body>    <sitemesh>        <mapping path="/**" decorator="/decorator.html"/>    </sitemesh></xml-body>

decorator.html指定了具体的布局:

<sitemesh:write property='head' /></head><body>    <h1 class='title'>        SiteMesh example site:        <sitemesh:write property='title' />    </h1>    <div class='mainBody'>        <sitemesh:write property='body' />    </div>    <div class='disclaimer'>Site disclaimer. This is an example.</div></body>

文件结构如下:
这里写图片描述
当访问hello.html时将会装饰指定的布局文件。