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);

posted @   zhjh256  阅读(442)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示