10分钟快速学会SiteMesh的使用

版权声明:如果转载或使用本博客,请标明出处 https://blog.csdn.net/Black1499/article/details/81868262

概述

  SiteMesh是一个用来在JSP中实现页面布局和装饰的框架组件,能够帮助网站开发人员较容易实现页面中动态内容和静态装饰外观的分离。

工作原理

  SiteMesh是基于Servlet的filter的,即过滤流。它是通过截取response,并进行装饰后再交付给客户。
其中涉及到两个名词: 装饰页面(decorator page)和 “被装饰页面(Content page)” , 即 SiteMesh通过对Content Page的装饰,最终得到页面布局和外观一致的页面,并返回给客户。

sitemesh运行环境需要:servlet, JDK 。

快速使用

1、下载与引用

下载地址:http://wiki.sitemesh.org/wiki/display/sitemesh/Download

引用:将下载好的包放到你的web项目下的web-inf文件夹下的lib文件夹

2、xml文件配置

在你的web.xml文件上面加入如下代码

    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

在web-inf目录下面新建decorators.xml文件,加入以下内容

<?xml version="1.0" encoding="utf-8" ?>
<decorators defaultdir="/decorators">    
</decorators>

3. 装饰页面的创建

在web目录下面新建一个decorators文件夹,在里面可以创建你自己的装饰页面,我这里创建的是book_index.jsp文件 ,同时我的所有的页面文件在web目录下面的jsp文件夹中

book_index.jsp页面需加入taglib标记

<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>

大概代码如下:

扫描二维码关注公众号,回复: 3646842 查看本文章
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div><!--这里是你的页头装饰-->
        <h1>header</h1>
    </div>
    <div><decorator:body /><!--被装饰的页面--></div>
    <div><!--这里是你的页脚装饰-->
        <h1>footer</h1>
    </div>
</body>
</html>

taglib声明允许JSP文件使用SiteMesh标记库。

:body将装饰页面的渲染内容放入装饰器中。

4、配置decorators.xml文件

这里以我的项目为例,大家可以根据自己的需求进行更改

<?xml version="1.0" encoding="utf-8" ?>
<decorators defaultdir="/decorators">
    <decorator name="book_index" page="book_index.jsp">
        <pattern>/jsp/*</pattern>
    </decorator>
</decorators>

5.启动项目,运行页面即可

猜你喜欢

转载自blog.csdn.net/Black1499/article/details/81868262