1,配置WebSiteMeshFilter过滤器
public class WebSiteMeshFilter extends ConfigurableSiteMeshFilter {
@Override
protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//对所有请求都添加index.jsp的装饰器页面
builder.addDecoratorPath("/*", "/WEB-INF/jsp/decorators/index.jsp");
//对login请求排除装饰器页面
builder.addExcludedPath("/login");
}
}
2,注册过滤器
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
WebSiteMeshFilter siteMeshFilter = new WebSiteMeshFilter();
//将装饰器过滤器添加到注册器
filterRegistrationBean.setFilter(siteMeshFilter);
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setEnabled(true);
return filterRegistrationBean;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WebViewFilter()).addPathPatterns("/*");
super.addInterceptors(registry);
}
}
3,在装饰页面index.jsp中添加被装饰页面的内容
<body>
<div class="wrapper">
<jsp:include page="index_top.jsp"></jsp:include>
<jsp:insclude page="index_left.jsp"></jsp:include>
<div class="wrap-content">
<sitemesh:write property='body' />
</div>
</div>
</body>
其中<sitemesh:write property='title' />表示将被装饰页面title部分写入
<sitemesh:write property='body' />表示将被装饰页面body部分写入
Sitemesh 3 简介
Sitemesh 是一个网页布局和修饰的框架,基于 Servlet 中的 Filter,类似于 ASP.NET 中的‘母版页’技术。参考:百度百科,相关类似技术:Apache Tiles。
官网:http://wiki.sitemesh.org/wiki/display/sitemesh/Home 。
Sitemesh 3 下载
最新版本:3.0.0-SNAPSHOT
① GitHub 地址:https://github.com/sitemesh/sitemesh3
配置 Sitemesh 3 过滤器
在 web.xml 中添加 Sitemesh Filter:
<web-app>...
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>org.sitemesh.config.ConfigurableSiteMeshFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
准备两个页面:demo.html 和 decorator.html
① demo.html - “被装饰的页面”,实际要呈现的内容页。
<!DOCTYPE html><html>
<head>
<title>内容页的标题</title></head>
<body>
内容页的body部分
</body>
</html>
② decorator.html - “装饰页面”,所谓的“母版页”。
<!DOCTYPE html>
<html>
<head>
<title>
<sitemesh:write property='title' /> - ltcms
</title>
<sitemesh:write property='head' />
</head>
<body>
<header>header</header>
<hr />
demo.html的title将被填充到这儿:
<sitemesh:write property='title' /><br />
demo.html的body将被填充到这儿:
<sitemesh:write property='body' />
<hr />
<footer>footer</footer>
</body>
</html>
添加 /WEB-INF/sitemesh3.xml
<?xml version="1.0" encoding="UTF-8"?>
<sitemesh>
<!-- 指明满足“/*”的页面,将被“/WEB-INF/views/decorators/decorator.html”所装饰 -->
<mapping path="/*" decorator="/WEB-INF/views/decorators/decorator.html" />
<!-- 指明满足“/exclude.jsp*”的页面,将被排除,不被装饰 -->
<mapping path="/exclude.jsp*" exclue="true" />
</sitemesh>
运行效果
访问 demo.html 页面,实际效果如下: