web開發中,一般的頁面布局都有統一的header,和footer,甚至統一側邊欄,只有中間主題部分可能不一樣,在每一個頁面中引入這些相同的部分不免有些麻煩,sitemesh3提供一種解決方案,通過不同的訪問連接匹配,可以是頁面布局統一風格。
實際上也就是做了兩件事:
1,對布局相同的頁面統一風格,只需要通過配置,即可
2,配置不同的布局,通過不同的連接匹配,進行不同的布局
西面就來看一下需要哪些配置:
1,首先加入jar包,可手動下載,maven項目可配置如下
<dependency> <groupId>org.sitemesh</groupId> <artifactId>sitemesh</artifactId> <version>3.0.0</version> </dependency>
2,web.xml中加入過濾器配置(匹配方式根據需要自行設置)
<filter> <filter-name>sitemesh</filter-name> <filter-class>org.sitemesh.config.ConfigurableSiteMeshFilter</filter-class> </filter> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
3,配置不同布局的裝飾頁面
<sitemesh:write property='head' /><!--引入主體頁面中的 head--> <sitemesh:write property='body' /><!--引入主體頁面中的 body-->
一般可能是這樣的
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 引入 css js --> <sitemesh:write property='head' /> </head> <body> <!-- 編寫統一風格的header 或者 include --> <sitemesh:write property='body' /> <!-- 編寫統一風格的footer 或者 include --> </body> </html>
4,添加sitemesh3配置文件(通過訪問連接配置裝飾模式)
<sitemesh> <mapping path="/*" decorator="/WEB-INF/decorators/content-decorator.jsp" /> <mapping path="/index.do" decorator="/WEB-INF/decorators/default-decorator.jsp" /> <mapping path="/login" decorator="/WEB-INF/decorators/login-decorator.jsp" /> <mapping path="/logout" decorator="/WEB-INF/decorators/login-decorator.jsp" /> </sitemesh>
5,連接訪問流程,如訪問的是localhost:8080/xxx/index.do spring中直接請求的index.jsp頁面
sitemesh中配置的裝飾器是default-decorator.jsp,因此index會通過default-decorator.jsp的裝飾后展現
但是,在使用中發現兩個問題:
1,sitemesh通過的是訪問連接匹配,如果在controller中將請求轉發則還會使用訪問時的配置,如訪問了/xxx/index.do,但我在這個controller中的詞請求轉發到/xxx/login.do,那么裝飾方式是default-decorator.jsp 而不是login-decorator.jsp
2,在裝飾器頁面 如default-decorator,和主體jsp如index.jsp 中有可能會產生js問題,具體原因也沒有找到,控制台不報錯,但有一些不通過sitemesh裝飾可執行的js,在sitemesh裝飾后無效。