velocity是apache基金会的项目。
public class HelloVelocity {
public static void main(String[] args) {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
Template t = ve.getTemplate("hellovelocity.vm");
VelocityContext ctx = new VelocityContext();
ctx.put("name", "velocity");
ctx.put("date", (new Date()).toString());
List temp = new ArrayList();
temp.add("1");
temp.add("2");
ctx.put( "list", temp);
StringWriter sw = new StringWriter();
t.merge(ctx, sw);
System.out.println(sw.toString());
}
}
vm文件如下
#set( $iAmVariable = "good!" )
Welcome $name to velocity.com
today is $date.
#foreach ($i in $list)
$i
#end
$iAmVariable
输出结果如下
Welcome velocity to velocity.com
today is Sun Mar 23 19:19:04 CST 2014.
1
2
good!