public class TestVelocity { public static String s = "abc"; public static int getNum(int i){return i*i; }; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Velocity.setProperty(Velocity.RESOURCE_LOADER, "class"); Velocity.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.setProperty(Velocity.ENCODING_DEFAULT, "GBK"); Velocity.setProperty(Velocity.INPUT_ENCODING, "GBK"); Velocity.setProperty(Velocity.OUTPUT_ENCODING, "GBK"); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("name", new String("Velocity")); List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); context.put("list", list); context.put("tmp", 20); context.put("cls", TestVelocity.class); Template template = null; //System.out.println(Test1.class.getResource("velocity/t1.vm").getPath()); template = Velocity.getTemplate("t1.vm"); StringWriter sw = new StringWriter(); template.merge( context, sw ); System.out.println(sw); } } 对应模板: #set($name="hello") ${name} $ !{xname} 当未设置xname的值时 什么都不显示 $ {vname} 当未设置vname的值时 就显示"$ {vname}" /${name} 转义 /#set($name="$strA$strB") 合并字符串 #foreach($tmp in $list) 循环次数:$velocityCount $tmp, #end # #遍历map---------- #foreach ( $key in $allProducts.keySet() ) Key: $key -> Value: $allProducts.get($key) #end $cls.s $cls.getNum(4) #if($tmp > 10)v>10 #elseif($tmp < 10)v<10 #else v==10 #end /#include( "asm.txt" )