关于velocity的使用,感觉最 困惑的是它的文件加载系统,他与java io的默认加载方式不同,而且对配置文件和模板文件使用不同的加载方式。感觉这个非常不友好!!!
下面是两种不同方法:
一,配置文件和模板文件放在jvm启动目录下,最简单的使用方法:
java code:
private static void testVMFileInRoot() throws Exception, IOException {
VelocityEngine ve = new VelocityEngine();
// 配置文件放在jvm启动路径下,在eclipse下是项目跟目录
ve.init("velocity.properties");
// 模板文件放在jvm启动路径下,在eclipse下是项目跟目录
Template template = ve.getTemplate("helloWorld.vm");
VelocityContext context = new VelocityContext();
context.put("name", "madding");
context.put("password", "123");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
writer.close();
}
velocity.propertis:
input.encoding=UTF-8
output.encoding=UTF-8
helloWorld.vm
你的
名字是:$name
密码是:$password
输出:
你的
名字是:madding
密码是:123
二,配置文件和模板文件位于classpath:
java:
private static void testVMFileInClasspath() throws Exception, IOException {
VelocityEngine ve = new VelocityEngine();
// 配置文件放在classpath路径下
ve.init("bin/vm/test/velocity.properties");
// 模板文件放在classpath路径下,在velocity.properties中指定file.resource.loader.path = ./bin
Template template = ve.getTemplate("vm/test/helloWorld.vm");
VelocityContext context = new VelocityContext();
context.put("name", "madding");
context.put("password", "123");
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
writer.close();
}
此时必须修改配置文件,即增加loader.paht的配置如下:
input.encoding=UTF-8
output.encoding=UTF-8
file.resource.loader.path = ./bin
但,我们发现,在java代码中,配置文件的路径和loader.path是无关的,因为你必须自己手动在前面加上bin/
所以,如果文件位于classpath中,velocity的用法感觉不是很友好。因为文件的加载方式让人产生了困惑。。。