velocity merge作为工具类从web上下文和jar加载模板的两种常见情形

很多时候,处于各种便利性或折衷或者通用性亦或是限制的原因,会借助于模板生成结果,在此介绍两种使用velocity merge的情形,第一种是和spring mvc一样,将模板放在velocityConfigurer属性指定的路径下,如:

<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/views/"/>
<property name="configLocation" value="/WEB-INF/conf/velocity.properties"/>
</bean>

这个时候,只要模板放在views下,然后直接借助于定义这个bean的mvc context即可,如下:

Map<String, Object> ctx = new HashMap<String, Object>();
ctx.put("appSnaps", list);
String result = VelocityEngineUtils.mergeTemplateIntoString(super.getVelocityConfigurer().getVelocityEngine(),Constants.FLAGMENT_PATH + "snap_id_select_option.vm", "GBK",ctx);

这是在web下使用比较便利的一种方式,也是推荐的。

还有些时候,我们可能需要以jar方式发布应用,此时模板也要打包到jar中,无法直接使用上述工具类进行合并。这时候需要给velocityengine传递上下文信息,如下所示:

        Properties properties=new Properties();
        properties.setProperty("resource.loader", "jar");
        properties.setProperty("jar.resource.loader.class", "org.apache.velocity.runtime.resource.loader.JarResourceLoader");
        properties.setProperty("jar.resource.loader.path", "jar:file:/WEB-INF/lib/XXX.jar");
        VelocityEngine velocityEngine=new VelocityEngine(properties);
        
        VelocityContext context=new VelocityContext();
        StringWriter writer=new StringWriter();
        //从 /WEB-INF/lib/XXX.jar中加载YYY.vm模板  vm.jar的目录结构为vm/YYY.vm
        velocityEngine.mergeTemplate("vm/hello.vm", "gbk", context, writer);

转载于:https://www.cnblogs.com/zhjh256/p/5892256.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值