velocity的使用

关于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的用法感觉不是很友好。因为文件的加载方式让人产生了困惑。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值