编写自定义的 Velocity 指令 #cache

来源:互联网 发布:电视推荐 知乎 编辑:程序博客网 时间:2024/05/20 08:42

[代码] CacheDirective.java

01/**
02 * Velocity模板上用于控制缓存的指令
03 * @author Winter Lau
04 * @date 2009-3-16 下午04:40:19
05 */
06public classCacheDirective extends Directive {
07 
08    finalstatic Hashtable<String,String> body_tpls =new Hashtable<String, String>();
09     
10    @Override
11    publicString getName() { return"cache"; } //指定指令的名称
12 
13    @Override
14    publicint getType() { returnBLOCK; } //指定指令类型为块指令
15 
16    /* (non-Javadoc)
17    * @see org.apache.velocity.runtime.directive.Directive#render()
18    */
19    @Override
20    publicboolean render(InternalContextAdapter context, Writer writer, Node node)
21        throwsIOException, ResourceNotFoundException, ParseErrorException,
22        MethodInvocationException
23    {
24        //获得缓存信息
25        SimpleNode sn_region = (SimpleNode) node.jjtGetChild(0);
26        String region = (String)sn_region.value(context);
27        SimpleNode sn_key = (SimpleNode) node.jjtGetChild(1);
28        Serializable key = (Serializable)sn_key.value(context);
29      
30        Node body = node.jjtGetChild(2);
31        //检查内容是否有变化
32        String tpl_key = key+"@"+region;
33        String body_tpl = body.literal();
34        String old_body_tpl = body_tpls.get(tpl_key);
35        String cache_html = CacheHelper.get(String.class, region, key);
36        if(cache_html ==null || !StringUtils.equals(body_tpl, old_body_tpl)){
37            StringWriter sw =new StringWriter();
38            body.render(context, sw);
39            cache_html = sw.toString();
40            CacheHelper.set(region, key, cache_html);
41            body_tpls.put(tpl_key, body_tpl);
42        }
43        writer.write(cache_html);
44        returntrue;
45    }
46}

[代码] 使用方法

01#cache("News","home")
02 ## 读取数据库中最新新闻并显示
03 <ul>
04 #foreach($news in $NewsTool.ListTopNews(10))
05    <li>
06     <spanclass='date'>
07$date.format("yyyy-MM-dd",${news.pub_time})
08</span>
09     <spanclass='title'>${news.title}</span>
10    </li>
11 #end
12 </ul>
13#end