sitemesh框架对页面进行布局和装饰
在实际看法中每写出的页面都需要页头和页脚,我们之前使用include将页面引用过来,这样如果页面一多得话,引用起来非常麻烦,所以这里使用sitemesh框架可以在页面中不用任何引入就可以加上页头页脚,这简化了我们的开发,sitemesh框架使用拦截器的思想来实现的,以后做开发只关注页面有什么数据,而网页的公共部分由装饰器来装饰装饰了之后再输出。下面是sitemesh框架的工作原理:
使用sitemesh的4个步骤:
1.导入架包,sitemesh-2.4.1.jar
2.在web.xml文件里边配置拦截器
3.sitemesh对谁进行装饰,要将decorators.xml配置文件加到工程中
4.写模板文件
web.xml文件配置如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <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-app>
<?xml version="1.0" encoding="ISO-8859-1"?>
<decorators defaultdir="/decorators">//模板的所在文件夹
<decorator name="main" page="template.jsp">//模板文件
<pattern>/*</pattern> //对所有页面进行装饰
</decorator>
</decorators>
template.jsp模板:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator"%>
<html>
<head>
<title><decorator:title/></title>
</head>
<body>
header.....<br/>
<decorator:body/>
footer....<br/>
</body>
</html>