打赏

sitemesh网页布局

看项目时发现对应页面下找不到侧栏部分代码,仔细观察后发现页面引入了sitemesh标签,查了下资料原来是页面用了sitemesh框架解!耦!了!

以前多个模块包含相同模块时总是include jsp文件,没感觉多么麻烦,但看了sitemesh,感觉可以非常简单!

sitemesh通过基于ServletFilter截取request和response,并给原始的页面介入一定的装饰,然后把结果返回给客户端,被装饰的页面并不知道sitemesh的装饰。

使用步骤如下:(sitemesh运行环境需要:servlet, JDK)

1,引入maven依赖

<dependency>
            <groupId>opensymphony</groupId>
            <artifactId>sitemesh</artifactId>
            <version>2.4.2</version>
</dependency>

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>
        <servlet-name>springmvcServlet</servlet-name>
    </filter-mapping>

<servlet>
        <servlet-name>springmvcServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>***</param-name>
            <param-value>***springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvcServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

3.在WEB-INF目录下添加sitemesh配置文件decorators.xml

<?xml version="1.0" encoding="utf-8"?>
<decorators defaultdir="/WEB-INF/layout">
    <!-- 此处用来定义不需要过滤的页面 -->
    <excludes>
        <pattern>/login</pattern>

   <pattern>/static/*</pattern> 
       <!--…… -->     
    </excludes>

    <!-- 定义用来装饰的页面 -->
    <decorator name="default" page="yanan7890.jsp">
        <pattern>/*</pattern>
    </decorator>
</decorators>

4.定义yanan7890.jsp页面,根据放在decorators defaultdir配置,放在/WEB-INF/layout/目录下

<%@page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="sitemesh" uri="http://www.opensymphony.com/sitemesh/decorator"%>
<!DOCTYPE html>
<html>
<head>

<title>SiteMesh示例-<sitemesh:title/></title>  <!-- 会自动替换为被过滤页面的title.sitemesh:title可选-->

<!--也可以引入需要复用的css和js-->

<link href="/***/.css" rel="stylesheet" type="text/css">
<script src="/***/.js"></script>
<sitemesh:head/><!--会把被过滤页面head里面的东西(除了title)放在这个地方-->
</head>
<body>

<%@ include file="/common/head.jsp"%>  

<div>
            <sitemesh:body/><!--被过滤的页面body里面的内容放在这里。-->
</div>
    <%@ include file="/common/foot.jsp"%>
</body>
</html>

如步骤3配置,如访问/login和/static下的页面不会装饰,访问其它页面会按照yanan7890.jsp拦截装饰

至此,大功告成!


参考文章:

1.http://cuisuqiang.iteye.com/blog/2066166

2.http://www.cnblogs.com/shanshouchen/archive/2012/08/10/2631819.html

3.http://baike.baidu.com/item/sitemesh

posted @ 2017-03-07 18:18  每天都要学一点  阅读(2585)  评论(0编辑  收藏  举报