sitemesh是jsp页面的一个前端框架,其主要思想是GOF设计模式中的装饰器模式,在笔者看来就是提高代码的重用性,减少重复的代码,方面工程的管理。具体的还不清楚,写下这博文知识为了巩固和记录自己今天使用sitemesh的一些笔记。

使用sitemesh的步骤:

  1. 导入 sitemesh的jar包,该包可以在官网上下载最新的稳定版。目前最新是sitemesh-2.4.2.jar

  2. 配置sitemesh的核心过滤器,主要用来拦截需要被装饰的页面。

  3. 在工程的WEB-INF目录下面创建一个decorators.xml文件,里面主要使用来声明需要被拦截装饰的页面和不需要拦截的页面。

  4. 之后就可以创建具体的页面来进行测试了,要使用装饰器的页面需要写meta属性来说明。具体内容看以下代码。


(1)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>


(2)decorators.xml文件

<decorators defaultdir="/layouts">
    
    <!-- 不需要过滤的请求 -->
    <excludes>
        <pattern>/static/*</pattern>  <!-- 表示在static文件夹下的所有页面都不需要进行装饰 -->
    </excludes>

    <!-- 定义装饰器要过滤的页面 -->
    <decorator name="default" page="default.jsp">     <!-- 表示对装饰器页面的声明 -->
        <pattern>/*</pattern>
    </decorator>
</decorators>

(3)default.jsp装饰器页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="sitemesh" uri="http://www.opensymphony.com/sitemesh/decorator"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<!-- 被装饰页面head部分内容将会被放进这里  -->

<title>SiteMesh 示例-<sitemesh:title/></title>    
<sitemesh:head/>            <!-- 被装饰页面head部分内容将会被放进这里  -->

</head>
<body>
    <h3>我是装饰器,我在被装饰页面的body内容之前</h3>
    <div id="content">
        <sitemesh:body/>    <!-- 被装饰页面body内容将会被放进这里  -->
    </div>
    <h3>我是装饰器,对页面进行装饰</h3>
</body>
</html>

(4)index.jsp测试页面

<%@ 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>我是index.jsp的title</title>
</head>
<body>
    <h3>我是index的body</h3>
</body>
</html>

(5)执行画面

该画面在附件