velocity需要在lib下面导入4个文件包,如下面jpg图片所示:
velocity-1.7.zip的文件包在下面也给了下载地址
------------HelloVelocity .java--------------------
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
public class HelloVelocity {
public static void main(String[] args) throws Exception {
//初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
ve.init();
//取得velocity的模版
Template t = ve.getTemplate("src/hellovelocity.vm"); //在src路劲下面放着的时间
//取得velocity的上下文context
VelocityContext context = new VelocityContext();
//把数据填入上下文
context.put("name","Liang");
context.put("bing","lujiebing");
context.put("date", (new Date()).toString());
//为后面的展示,提前输入List数值
List temp = new ArrayList();
temp.add("1");
temp.add("2");
context.put("list", temp);
//hashtable
Hashtable table=new Hashtable();
table.put("a", 1);
table.put("b", 1);
table.put("c", 1);
context.put("table", table);
//javabean
context.put("person",new PersonBean("xuli","1234"));
//输出流
StringWriter writer = new StringWriter();
//转换输出
t.merge(context, writer);
System.out.println(writer.toString());
}
}
---------helloVelocity.vm---------------------
Welcome $name to Javayou.com!
today is $date.
#set($bing = "lujie")
welcome $bing to see you!
#foreach( $product in $list )
<$velocityCount> $product
#end
#foreach( $key in $table.keySet() )
$key value: $table.get($key)
#end
Address: $person.name