使用sitemesh的步骤

1. 添加jar文件到classpath

2. 在web.xml中增加过滤器

  1. <!-- Sitemesh -->
  2. <filter>
  3. <filter-name>sitemesh</filter-name>
  4. <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
  5. </filter>
  6. <filter-mapping>
  7. <filter-name>sitemesh</filter-name>
  8. <url-pattern>/*</url-pattern>
  9. </filter-mapping>

3. 在/WEB-INF中创建decorator.xml文件

  1. <decorators defaultdir="/decorators">
  2. <decorator name="main" page="main.jsp">
  3. <pattern>/*</pattern>
  4. </decorator>
  5. </decorators>

defaultdir:指定了装饰页面的存放路径
    在这里可以使用<decorator>标签配置多个装饰器

4. 另外有一个可选的sitemesh.xml文件,放在/WEB-INF目录下。如果没用,则默认读取sitemesh.jar文件中的sitemesh-default.xml文件。这个文件在jar:com.opensymphony.module.sitemesh.factory包中。

在这个文件中可以指定使用那些mapper对象来装饰页面,也可以扩展自己的Mapper类。 sitemesh自带的mapper类放在com.opensymphony.module.sitemesh.mapper包中,可以供大家选择使用。

5. 这里是今天学习备注的重点 ,com.opensymphony.module.sitemesh.mapper.PageDecoratorMapper 这个类的使用。

在sitemesh-default.xml中,可以看到已经声明了这个类,并且可以通过查阅API来获得其使用方法。

在这个文件中可以看到配置了这个类的两个属性

  1. property.1=meta.decorator
  2. property.2=decorator

通过查阅API可以找到,只要html文件中包含

  1. <meta name="decorator" content="decoratorname">
  2. <meta name="meta.decorator" content="decoratorname">

就可以应用相应的装饰器,而不必在decorator.xml中使用<pattern>来规定哪些页面使用哪些装饰器。

  1. <decorators defaultdir="/decorators">
  2. <decorator name="main" page="main.jsp">
  3. </decorator>
  4. </decorators>

6. 一点联想:

在com.opensymphony.module.sitemesh.mapper包中我看到了一个叫CookieDecoratorMapper的类,话说可以在用户的cookie中指定装饰器的名字。

这样我们可以通过扩展来实现基于用于的个人喜好设定,用户可以自己选择需要应用的装饰器(有点类似QQ空间选择个性主页模板),把装饰器的的名称存放起来,当浏览页面的时候自动去读取这个值以实现主页风格的动态切换。只是有个这个想法,还没有付诸行动,有兴趣的朋友可以试试看。

05-11 16:25
查看更多