在工程中引入SiteMesh的必要jar包
<dependency>
<groupId>opensymphony</groupId>
<artifactId>sitemesh</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-sitemesh-plugin</artifactId>
<version>2.3.28.1</version>
</dependency>
修改你的web.xml,在里面加入sitemesh的过滤器,示例代码如下:
<filter>
<filter-name>StrutsPrepareFilter</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
</filter>
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
</filter>
<filter>
<filter-name>StrutsExecuteFilter</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>StrutsPrepareFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>*.xhtml</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>StrutsExecuteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意过滤器的位置:应该在struts2的org.apache.struts2.dispatcher.ActionContextCleanUp过滤器之后,org.apache.struts2.dispatcher.FilterDispatcher过滤器之前,否则会有问题;
在下载的SiteMesh包中找到sitemesh.xml,(\sitemesh-2.4\src\example-webapp\WEB-INF目录下就有)
在sitemesh.xml文件中有一个property结点(如下),该结点指定了decorators.xml在工程中的位置,让sitemesh.xml能找到他;
按照此路径新建decorators.xml文件,当然这个路径你可以任意改变,只要property结点的value值与其匹配就行;
<property name="decorators-file" value="/WEB-INF/decorators.xml"/>
在Web-INF目录下新建decorators目录,然后新建三个JSP,一个是默认,一个输出头,一个输出尾,默认页面引用其他两个。
默认页面default.jsp:
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="sitemesh" uri="http://www.opensymphony.com/sitemesh/decorator" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>SiteMesh示例-<sitemesh:title/></title>
<sitemesh:head/>
</head>
<body>
<%@ include file="header.jsp"%>
<div id="content">
<sitemesh:body/>
</div>
<%@ include file="footer.jsp"%>
</body>
</html><span>
</span>
简单说明:
- 引入了SiteMesh标签。
- <sitemesh:title/> 会自动替换为被过滤页面的title。
- <sitemesh:head/> 会把被过滤页面head里面的东西(除了title)放在这个地方。
- <sitemesh:body/> 被过滤的页面body里面的内容放在这里。
- 头部引入js和css,都可以在其他重用。
你总不能这么不讲道理吧!
大家放心吧,SiteMesh早就考虑到这一点了,上面第5步说道的decorators.xml这个时候就起到作用了!
下面是我的decorators.xml:
decorators.xml有两个主要的结点:
decorator结点指定了模板的位置和文件名,通过pattern来指定哪些路径引用哪个模板
excludes结点则指定了哪些路径的请求不使用任何模板
两种方法
1:
2: