Apache Velocity简单例子

http://jakarta.apache.org/site/binindex.cgi上下载Velocity 包, 使用jar包:velocity-1.7.jar、avalon-logkit-2.1.jar、commons-collections-3.2.1.jar、commons-lang-2.4.jar、commons-logging-1.1.jar

1、Java类

package com.velocity;

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class HelloWorld {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// 初始化并取得Velocity引擎
		VelocityEngine ve = new VelocityEngine();

		ve.init();
		// 取得velocity的模版,放到工程名下一级目录
		Template template = ve.getTemplate("hellovelocity.vm");
		// 取得velocity的上下文context
		VelocityContext context = new VelocityContext();
		// 把数据填入上下文
		context.put("name", "zhangsan");
		// 输出流
		StringWriter writer = new StringWriter();
		// 转换输出
		template.merge(context, writer);
		System.out.println(writer.toString());

	}

}

 2、hellovelocity.vm

Welcome  $name 

参考:http://www.iteye.com/topic/135506

猜你喜欢

转载自wanxiaotao12-126-com.iteye.com/blog/1743929