您的位置:首页 > 其它

用sitemesh来装饰动态的左侧菜单和内容部分

2011-07-17 08:35 232 查看
sitemmesh是一个页面装饰框架,利用它可以很简单的对整个系统进行统一架构装饰,比如一个应用系统的web层可能就是top+left+content+footer四个部分组成(下图)



使用sitemesh定义好一个统一的框架后,程序员只需要关注动态的内容部分就可以了,而不需要在每个页面去单独的include一堆的footer,left,header之类的公共部分--框架只是一个工具,存在的目的在于提高生产率,减少重复劳动。

以下是这个sitemsh的装饰页面源码

<%@ page contentType="text/html; charset=GBK"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<html>
<head>
<title><decorator:title default="装饰器页面..." /></title>
<decorator:head />
</head>
<body>
<jsp:include page="/header.jsp"></jsp:include>
<jsp:include page="/left.jsp"></jsp:include>
<decorator:body />
<jsp:include page="/footer.jsp"></jsp:include>
</body>
</html>
非常简洁明了,把页面拆成可复用的组件单元,通过jsp include来引入

实际生产中的问题

做一个系统,可能有多个模块组成,通常会给每个模块分配一个namespace或package,如一个用户管理系统可能有user和system两个模块组成,那么其访问链接很可能是http://localhost:8080/user/userList.action和http://localhost:8080/system/sysConfig.action,这个时候对于不同模块其对应的左侧菜单或header部分很可能是不同的,如user模块左侧菜单是创建用户,修改密码,而system模块则是配置系统参数,发送email等,怎样用sitemesh来实现对于不同模块加载不同的左侧菜单的目的呢?通常有两种方式

1.创建多个decorator,为每个模块都创建一个单独的decorator,在decorator里加载不同的left菜单

优势:配置简单,理解成本比较小

劣势:对于绝大数系统来说,多个系统模块的模块一般都是统一的,配置多个decorator意味着创建个装饰页面,这些装饰页面里可能95%以上的代码都是一样的,不同点在于include不同的left.jsp文件

2.一个decorator,使用动态参数来动态加载哪个left.jps文件

实现原理:当前请求所在模块作为参数传递给sitemesh,sitemesh读取该参数,并去对应模块加载各自的left.jsp文件,这样就存在以下的问题

a)所在模块信息存放在哪里?

通常的做法是在动态页面的<head>元素中添加一个<meta>元素,meta元素其实可以简单的理解成一个key-value的数据节点,如在user模块的创建用户页面/user/createUser.jsp里添加

<meta name="moduleName" content="user"/>,而在system模块的系统配置页面/system/sysConfig.jsp页面添加如下<meta name="moduleName" content="system"/>

b)sitemsh怎么读?

对于所有的jsp页面,根据jsp页面所在的模块不同,也存放为不同的页面下,这里做一个统一的命名约束,对于各个模块的左侧菜单,都统一命名为left.jsp,其目录结构如下

/user/left.jsp

/user/createUser.jsp

/system/left.jsp

/system/sysConfig.jsp

有了这样的命名约束后,我们就可以在sitemesh的装饰页面做文章了

<%@ page contentType="text/html; charset=GBK"%>
<%@ taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="decorator" %>
<html>
<head>
<title><decorator:title default="装饰器页面..." /></title>
<decorator:head />
</head>
<body>
<jsp:include page="/header.jsp"></jsp:include>
<decorator:usePage id="thePage" /> <!-- 把当前页面赋值给thePage这个变量-->
<jsp:include page="/<%=thePage.getProperty("meta.moduleName")%>/left.jsp"></jsp:include>
<decorator:body />
<jsp:include page="/footer.jsp"></jsp:include>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: