sitemesh官方地址
简介
sitemesh应用Decorator模式,用filter截取request和response,把页面组件head,content,banner结合为一个完整的视图。通常我们都是用include标签在每个jsp页面中来不断的包含各种header, stylesheet, scripts and footer,在sitemesh的帮助下,我们不用在每个jsp页面中写这些代码了,方面项目的维护。
image.png
引入jar包
<!-- maven -->
<dependency>
<groupId>opensymphony</groupId>
<artifactId>sitemesh</artifactId>
<version>2.4.2</version>
</dependency>
配置filter
在web.xml按如下代码配置filter,对应url返回的view都会被sitemesh处理。
<!-- 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>
配置decorator
在WEB-INF目录下新建decorators.xml,defaultdir定义装饰器所在的根目录。
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/WEB-INF/layout/">
<!-- 不被装饰的url -->
<excludes>
<pattern>/static/*</pattern>
</excludes>
<!-- 装饰器定义 -->
<decorator name="default" page="base.jsp">
<pattern>*</pattern>
<pattern>/example</pattern>
<pattern>/example/example</pattern>
<pattern>/example/*</pattern>
<pattern>/**/example</pattern>
</decorator>
</decorators>
引入decorator标签
decorator标签有两种引入方式:
1.在web.xml文件中配置taglib
<taglib>
<taglib-uri>sitemesh-decorator</taglib-uri>
<taglib-location>/WEB-INF/sitemesh-decorator.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>sitemesh-page</taglib-uri>
<taglib-location>/WEB-INF/sitemesh-page.tld</taglib-location>
</taglib>
在对应的taglib-location下复制tld文件(可在jar包里找到)。
image.png
装饰器里引入taglib
<%@ taglib uri="sitemesh-decorator" prefix="decorator"%>
<%@ taglib uri="sitemesh-page" prefix="page"%>
uri与taglib-uri对应
2.快速引入
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
装饰器
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><decorator:title default="首页"/>-example</title>
<decorator:head/>
</head>
<body>
<decorator:body/>
</body>
</html>
被装饰页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>welcome!</title>
</head>
<body>
<p>welcome to example !</p>
</body>
</html>
网友评论