sitemesh入门教程

Sitemesh入门

Sitemesh是一种页面装饰技术:它通过过滤器(filter)来拦截页面访问,据被访问页面的URL找到合适的装饰模板等

一、基本概念

1.运行流程

PC访问请求 --> web过滤器拦截 -->根据访问页面url选择合适的模板 --> 提取被访问页面内容放在模板中指定的位置 -->响应给PC端

2.流程图

image-20210705165103353

使用sitemesh后,页面分为两种类型,模板页面和普通页面,模板页面是用于修饰普通页面的。

二、配置与应用

1.在web.xml中配置过滤器和标签库

<!-- 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>
</filter-mapping>

2.创建装饰模板配置文件,在web/目录下创建decorators.xml

<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/decorators">
    <decorator name="basic-theme" page="basic-theme.jsp">
        <pattern>/data/*</pattern>
    </decorator>
</decorators>

3.创建模板文件,在web/下创建decorators目录,创建一个模板文件 basic-theme.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<!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">
<head>
    <title><decorator:title /></title>
    <decorator:head />
</head>
<body>
<h1>Header</h1>
<p><b>Navigation</b></p>
<hr />
<decorator:body />
<hr />
<h1>Footer</b></h1>
</body>
</html>
  • <decorator:title /> 标签表示在此处放置响应页面内容的title标签内容
  • <decorator:body /> 标签表示在此处放置响应页面内容的body标签内容
  • <decorator:head /> 标签表示在此处放置响应页面内容的head标签内容

4.创建普通页面,在web/目录下创建data目录,在此目录创建menu.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<!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">
<head>
    <title>Menu</title>
</head>
<body>
<h1>Beverages</h1>
<p>Cappucino $3.25</p>
<p>Latte $3.35</p>
<p>Espresso $2.00</p>
<p>Mocha $3.50</p>
</body>
</html>

5.启动运行服务,查看menu.jsp页面是否有被修饰

image-20210706094842782

扩展内容

exclude标签可以排除一些路径不被装饰模板修饰

<decorators defaultdir="/decorators">
    <decorator name="basic-theme" page="basic-theme.jsp">
        <pattern>/data/*</pattern>
    </decorator>
    <excludes>
        <pattern>*hours.jsp</pattern>
    </excludes>
</decorators>

参考

https://www.jb51.net/web/70208.html

https://zhuanlan.zhihu.com/p/104202143

https://blog.csdn.net/weixin_36380516/article/details/74943229

官方文档

posted @ 2021-07-06 10:05  王希知  阅读(354)  评论(0编辑  收藏  举报