一.导入依赖
导入在中央库中的依赖方法如下
<dependency> <groupId>opensymphony</groupId> <artifactId>sitemesh</artifactId> <version>2.4.2</version> <scope>runtime</scope> </dependency>
最新版的SiteMesh2
<repositories> <repository> <id>SiteMesh</id> <name>SiteMesh Repository</name> <url>http://maven-us.nuxeo.org/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>opensymphony</groupId> <artifactId>sitemesh</artifactId> <version>2.5-atlassian-9</version> </dependency> </dependencies>
二.web.xml中添加Filter
在web.xml中添加下面这个filter
<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>
该filter可以放在其它filter后面,比如org.springframework.web.filter.CharacterEncodingFilter
三.装饰器decorator
编写装饰器JSP页面,比如
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %> <html> <head> <title>My Site - <decorator:title default="Welcome!" /></title> <decorator:head /> </head> <body> <decorator:body /> </body> </html>
注意<decorator:title default="Welcome!" /> <decorator:head /> <decorator:body />
四.配置文件decorators.xml
通过配置文件通知
<?xml version="1.0" encoding="UTF-8"?> <decorators defaultdir="/WEB-INF/layouts"> <!-- 不进行装饰的路径 --> <excludes> <pattern>/static/*</pattern> <pattern>/api/*</pattern> </excludes> <!-- 默认装饰器 --> <decorator name="default" page="decorator.jsp"> <pattern>/*</pattern> </decorator> <decorator name="anotherdecorator" page="decorator2.jsp"> <pattern>/site*</pattern> </decorator> <decorator name="htmldecorator" page="html.jsp"> <pattern>*.html</pattern> <pattern>*.htm</pattern> </decorator> <decorator name="none"> <!-- These files will not get decorated. --> <pattern>/none/*</pattern> </decorator> </decorators>
1.理论上SiteMesh只会搞那些MIME type为html的页面,但在配置里先exclude掉一些静态内容和Restful API的路径会更省心;
2.根据路径匹配来选用装饰器,并按照从左到右匹配的方式,*号的级别最低,比如例子中(1) /site* 或 *.html 均匹配不上时才会使用 default装饰器 ; (2)/site.html 会使用anotherdecorator装饰器;