在ssh项目中中引入sitemesh框架,实现装饰页和内容的分离,个人理解为sitemesh过滤了请求的连接,对于需要装饰的页面加载完装饰页面的部分,实际上有点儿像include这个属性,不同的是include直接把jsp整体加进去,而sitemesh的decorator是分title、head、和body的内容分别嵌套进入装饰页。
不过需要注意的是到浏览器端js和css等加载的顺序,被装饰的页面的js、css以及JavaScript是排在装饰页面内包含的js、css等的前面的,所以如果装饰页面和被装饰页面都有对一个组件的定义,那么这个组件最后显示的效果是被装饰页面里面定义的效果。
现实的例子是我在被装饰页面里面写了表格的初始化,而在装饰页面里面没有写,结果是刷新一下,效果闪一下又不见了。而如果在装饰页面里面定写了初始化,被装饰页面就可以省略了。
1、在项目中引入sitemesh
2、在web.xml配置添加过滤器
<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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
3、添加sitemesh配置文件:decorators.xml
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/decorators">
<excludes>
<pattern>/login.*</pattern>
<pattern>/error.*</pattern>
</excludes>
<decorator name="main" page="MainBody.jsp">
<pattern>/WEB-INF/ServiceManage/*</pattern>
</decorator>
</decorators>
exclude代表排除不要装饰的页面,而decorator表示装饰的属性,page里面的jsp表示你的装饰页
pattern表示你要被装饰页面的路径,把你要装饰的页面放在这个目录下面,当然也可以定义多个
4、装饰页面MainBody.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<base href="<%=basePath%>"/>
<decorator:head></decorator:head>
<title>XX系统—— <decorator:title default="欢迎你!"></decorator:title></title>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="expires" content="0"/>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"/>
<meta http-equiv="description" content="This is my page"/>
<link rel="stylesheet" type="text/css" href="styles.css"/>
<script language=javascript src="clock.js"></script>
<%java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
java.util.Date currentTime = new java.util.Date();
String time = simpleDateFormat.format(currentTime).toString(); %>
</head>
<body οnlοad="showtime()">
<div id="container">
<div id="header">
XX系统
</div>
<div id="main">
<div id="menu" >
<%@include file="/menus.jsp" %>
</div>
<div id="content">
<decorator:body></decorator:body>
<br/><a href=Login.jsp>注销</a>
</div>
</div>
<div id="footer" >
版权所有
<form name=clock >
<input name="thetime" style="font-size: 9pt;color:#000000;border:0" size="30"/>
</form>
<%=time%>
</div>
</div>
</body>
</html>