不知道语法的可以先看语法,官网:
需要的jar包:commons-collections.jar, commons-io.jar , commons-lang.jar, commons-logging.jar, velocity-1.5.jar。 因公司不能下载所以采用的是1.5, 最新的是1.7 。
mport java.io.StringWriter;
import java.util.ArrayList; import java.util.List; import java.util.Properties;import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException;public class Test {
/**
* @param args * @throws Exception * @throws ParseErrorException * @throws ResourceNotFoundException */ public static void main(String[] args) throws ResourceNotFoundException, ParseErrorException, Exception { // 初始化并取得Velocity引擎 String fileDir = "C:\\workspace3.7\\TestTemplate\\template"; VelocityEngine engine = new VelocityEngine(); Properties properties = new Properties(); properties.setProperty(engine.FILE_RESOURCE_LOADER_PATH, fileDir); engine.init(properties); //创建context VelocityContext context = new VelocityContext(); List<String> arryOne = new ArrayList<String>(); List<String> arryTwo = new ArrayList<String>(); arryOne.add("aaa"); arryOne.add("bbb"); arryOne.add("ccc"); arryTwo.add("AAA"); arryTwo.add("BBB"); arryTwo.add("CCC"); //向context中添加数据 context.put("arryOne", arryOne); context.put("arryTwo", arryTwo); //获取模板文件 Template template = engine.getTemplate("HelloVelocity.vm"); //读取模板文件并雪茹到writer中 StringWriter writer = new StringWriter(); template.merge(context, writer); String result = writer.toString(); System.out.println(result); }}
HelloVelocity.vm中的内容为
#foreach($temp in ${arryOne})
#set($index = $velocityCount - 1) ${temp}-${arryTwo.get($index)} #end打印结果为:
aaa-AAA
bbb-BBB ccc-CCC
这样就可以改变模板文件进行测试了。