10分鐘快速學會SiteMesh的使用
阿新 • • 發佈:2018-11-08
概述
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" %>
大概程式碼如下:
<?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>