Java SiteMesh新手學習教程程式碼案例
阿新 • • 發佈:2020-10-19
官網:http://wiki.sitemesh.org/wiki/display/sitemesh/Home
也可以下載官方的示例Demo參考和學習,這裡我只做一個簡單示例,演示最基本的使用
首先就是加Jar包,我用的是sitemesh-2.4.2.jar,然後在web.xml中增加過濾器:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <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下:
<?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:
<%@ 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:
<%@ 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則不會攔截處理
根據頁面看實際效果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。