Java SiteMesh新手学习教程代码案例

IT教程2年前 (2021)发布 tang
76 0 0
马哥源码

马哥资源网
这篇文章主要介绍了Java SiteMesh新手学习教程代码案例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

官网:http://wiki.sitemesh.org/wiki/display/sitemesh/Home

也可以下载官方的示例Demo参考和学习,这里我只做一个简单示例,演示最基本的使用

首先就是加Jar包,我用的是sitemesh-2.4.2.jar,然后在web.xml中增加过滤器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <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>
</web-app>

增加SiteMesh配置文件decorators.xml,该文件放在WEB-INF下:

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/layouts/">
 <!-- 不需要过滤的请求 -->
 <excludes>
 <pattern>/static/*</pattern>
 <pattern>/remote/*</pattern>
 </excludes>
 <!-- 定义装饰器要过滤的页面 -->
 <decorator name="default" page="default.jsp">
 <pattern>/*</pattern>
 </decorator>
</decorators>

在根目录下新建文件夹layouts,然后新建三个JSP,一个是默认,一个输出头,一个输出尾,默认页面引用其他两个。
默认页面default.jsp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="sitemesh" uri="http://www.opensymphony.com/sitemesh/decorator" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>SiteMesh示例-<sitemesh:title/></title>
<sitemesh:head/>
</head>
<body>
 <%@ include file="/layouts/header.jsp"%>
 <div id="content">
  <sitemesh:body/>
 </div>
 <%@ include file="/layouts/footer.jsp"%>
</body>
</html>

简单说明:

  • 引入了SiteMesh标签。
  • <sitemesh:title/> 会自动替换为被过滤页面的title。
  • <sitemesh:head/> 会把被过滤页面head里面的东西(除了title)放在这个地方。
  • <sitemesh:body/> 被过滤的页面body里面的内容放在这里。

头部引入js和css,都可以在其他重用。

头页面header.jsp:

<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>

菜单信息

尾页面footer.jsp:

<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%>
版权信息

在根下新建一个文件夹static,用于实验是否拦截,在该文件夹下新建JSP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>" rel="external nofollow" >
  <title>有人拦截我吗?</title>
 </head>
 <body>
  有人拦截我吗?
 </body>
</html>

访问:http://127.0.0.1:8080/sitemesh/index.jsp这个会拦截

访问:http://127.0.0.1:8080/sitemesh/static/index.jsp则不会拦截处理

根据页面看实际效果

© 版权声明

相关文章

暂无评论

暂无评论...