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