页面跟布局

1 include

  • <jsp:include>
  • <%@include file="xxx">

2 SiteMesh

首先,将 jar 包添加到项目中:

opensymphony:sitemesh:2.4.2

其次,在 web.xml 中添加过滤器,将所有请求交给 SiteMesh 过滤

com.opensymphony.sitemesh.webapp.SiteMeshFilter

然后,添加 SiteMesh 的配置文件 WEB-INF/decorators.xml:

<?xml version="1.0" encoding="utf-8" ?>
<decorators defaultdir="/jsp/layouts/">
  <!-- 先定义不过滤的页面,即排除页面 -->
  <excludes>
    <pattern>/assets/*</pattern>
  </excludes>

  <!-- 定义需要修饰的页面 -->
  <decorator name="book" page="book_tpl.jsp">
    <pattern>/*</pattern>
  </decorator>
</decorators>

之后,创建模板文件 jsp/layouts/book_tpl.jsp:

<!doctype html>
<html lang="en">
  <head>
    <title><sitemesh:title /></title>
    <sitemesh:head />
  </head>
  <body>
    <header>
      <%@include file="book_header.jsp" />
    </header>

    <div>
      <sitemesh:body />
    </div>

    <footer>
      <%@include file="book_footer.jsp" />
    </footer>


    <!-- 其他用法 -->

    <!-- 可以通过 meta 在页面之间传递数据 -->
    <!-- <meta name='xxx' content='ksjfkjskf' -->
    <decorator:getProperty property="meta.xxx" />

    <!-- 可以通过 usePage 引用到原始页面的 jsp 对象 -->
    <decorator:usePage id="myPage" />
    <%= myPage.getRequest().getAttribute("xxx") %>

    <!-- 其他,自行总结 -->
  </body>
</html>

最后,就可以使用了。

3 Apache Tile

另一款比较流行的页面布局插件。它比 SiteMesh 复杂,但更灵活。

Author: unname

Created: 2019-03-22 周五 01:32

Go ahead, never stop.