Velocity读取模板文件的方法[转]

我用的是velocity-1.6.4,官方自带的Example.java中的加载Velocity模板文件的代码有问题,原始代码为:

Velocity.init("velocity.properties");

试着运行说找不到velocity.properties。然后我改成绝对路径,还是不行。

最后查到,加载Velocity模板文件需要Velocity init一个属性类,以下是转的:

 

在J2EE应用开发中,经常将Velocity模板文件打包在JAR文件中一起部署,但是Velocity的缺省行为是从OS的文件系统中读取模板文件,使用FileResourceLoader来读取模板文件

如果要改为从classpath中获取模板文件,那么要对Velocity的初始化参数进行调整:
VelocityEngine ve=new VelocityEngine();
//可选值:"class"--从classpath中读取,"file"--从文件系统中读取
ve.setProperty("resource.loader", "class");
//如果从文件系统中读取模板,那么属性值为org.apache.velocity.runtime.resource.loader.FileResourceLoader
ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init();
Template t=ve.getTemplate("/vmpath/test.vm");

另外,Velocity缺省提供了多种读取模板的方法,列举如下,具体内容可以参考发布包中的Javadoc:
org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader
org.apache.velocity.runtime.resource.loader.JarResourceLoader
org.apache.velocity.runtime.resource.loader.StringResourceLoader
org.apache.velocity.runtime.resource.loader.URLResourceLoader

velocity做为一种模板语言,在这个方面也具备自己的实现方式,那就是velocimacro
#velocitymacro 的模板
velocimacro.library=macros.vm
velocimacro.library.autoreload = true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值