//擴展入口Filter實現: package lab.s2jh.core.web.sitemesh; import org.sitemesh.DecoratorSelector; import org.sitemesh.builder.SiteMeshFilterBuilder; import org.sitemesh.config.ConfigurableSiteMeshFilter; import org.sitemesh.webapp.WebAppContext; /** * 擴展實現注入基於request參數decorator值進行動態定位裝飾器的選擇器 */ public class ParamConfigurableSiteMeshFilter extends ConfigurableSiteMeshFilter { protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) { //獲取原有默認配置裝飾選擇器 DecoratorSelector<WebAppContext> defaultDecoratorSelector = builder.getDecoratorSelector(); //賦給自定義裝飾選擇器,則自定義規則未匹配時調用默認選擇器獲取 builder.setCustomDecoratorSelector(new ParamDecoratorSelector(defaultDecoratorSelector)); } }
//定製裝飾選擇器實現: package lab.s2jh.core.web.sitemesh; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.sitemesh.DecoratorSelector; import org.sitemesh.content.Content; import org.sitemesh.webapp.WebAppContext; /** * 基於request參數decorator值進行動態定位裝飾器的選擇器 * 若是decorator參數有值,則返回"/WEB-INF/views/layouts/" + decorator + ".jsp"做爲目標裝飾模板頁面 */ public class ParamDecoratorSelector implements DecoratorSelector<WebAppContext> { private DecoratorSelector<WebAppContext> defaultDecoratorSelector; public ParamDecoratorSelector(DecoratorSelector<WebAppContext> defaultDecoratorSelector) { this.defaultDecoratorSelector = defaultDecoratorSelector; } public String[] selectDecoratorPaths(Content content, WebAppContext context) throws IOException { // build decorator based on the request HttpServletRequest request = context.getRequest(); String decorator = request.getParameter("decorator"); if (StringUtils.isNotBlank(decorator)) { //按照參數值返回對應路徑下面的jsp裝飾模板頁碼 return new String[] { "/WEB-INF/views/layouts/" + decorator + ".jsp" }; } // Otherwise, fallback to the standard configuration return defaultDecoratorSelector.selectDecoratorPaths(content, context); } }
<!-- 調整web.xml配置: --> <filter> <filter-name>sitemeshFilter</filter-name> <filter-class>lab.s2jh.core.web.sitemesh.ParamConfigurableSiteMeshFilter</filter-class> </filter> <filter-mapping> <filter-name>sitemeshFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>