最近使用Velocity模板引擎,写一个maven项目Coding生成工具。
对基于Java的模板引擎Velocity的demo总结如下:
Step1. 创建Maven项目,添加如下velocity的dependency到pom.xml中
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
Step2. 创建模板文件HelloVelocity.vm
#set( $iAmVariable = "good!" )
Welcome $name to velocity.com
today is $date.
$iAmVariable
Step3. 创建Java文件HelloVelocity.java
package com.bestpay.velocity_demo;
import java.io.StringWriter;
import java.util.Date;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
/**
* First demo of using velocity
*/
public class HelloVelocity {
public static void main( String[] args ){
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngine.init();
Template template = velocityEngine.getTemplate("com/bestpay/velocity_demo/HelloVelocity.vm", "UTF-8");
VelocityContext context = new VelocityContext();
context.put("name", "liang01.ma");
context.put("date", new Date().toString());
StringWriter writer = new StringWriter();
template.merge(context, writer);
System.out.println(writer.toString());
}
}
测试结果
Welcome liang01.ma to velocity.com
today is Wed Jul 20 16:57:49 CST 2016.
good!