velocity 入门实例
1 java文件
package com.test;import java.io.StringWriter; import java.util.*;import org.apache.velocity.app.Velocity;import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; public class VelTest {public static void main(String[] args) throws Exception { //初始化并取得Velocity引擎 VelocityEngine ve = new VelocityEngine(); //Properties p =new Properties(); //p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");//ve.init(p); //ve.setProperty(Velocity.RESOURCE_LOADER, "class");//ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); //ve.init();Properties p =new Properties();p.put(Velocity.FILE_RESOURCE_LOADER_PATH, "D:/workspace/velocity/src/");ve.init(p);//取得velocity的模版 Template t = ve.getTemplate("com/test/example2.vm","gbk"); //取得velocity的上下文context VelocityContext context = new VelocityContext(); //把数据填入上下文 context.put("name", "zhaozhi3758"); //为后面的展示,提前输入List数值 也可以解析pojoList temp = new ArrayList(); temp.add("1"); temp.add("2"); context.put("list", temp); Map velMap =new HashMap();velMap.put("key1", "极品家丁");velMap.put("key2", "斗破苍穹");context.put("map", velMap); List lmList = new ArrayList();Map l1Map =new HashMap();l1Map.put("list1", "listValue1");l1Map.put("list11", "listValue11");lmList.add(l1Map);Map l2Map =new HashMap();l1Map.put("list2", "listValue2");l1Map.put("list22", "listValue22");lmList.add(l2Map);context.put("listmap", lmList);//输出流 StringWriter writer = new StringWriter(); //转换输出 t.merge(context, writer); System.out.println(writer.toString()); }}2 模板文件
#parse("/com/test/example1.vm")//--------------直接设值----------------#set($condition = true)#if ($condition) 条件 is true!#else 条件 is false!#end//--------------context 中设值---------- 欢迎来自$name$project的工程!//------------遍历list------------------#foreach($name in $list ) $name#end//------------遍历map------------------#foreach($param in $map.keySet()) key:$param --> value: $map.get($param)#end//------------遍历list<map>------------------#set ($i=0)#foreach($lmap in $listmap) #foreach($inMap in $lmap.keySet())key:$inMap --> value: $lmap.get($inMap) #end #set($i=$i+1)#end