Velocity是一個基於java的模板引擎(template engine)。它允許任何人僅僅簡單的使用範本語言(template language)來引用由java代碼定義的對象。
現在我們就來看這個小例子:
1. 建立一個Velocity模板,以vm結尾,例子中模板檔案為TaxReportXml.vm,內容如下:
<?xml version="1.0" encoding="utf-8"?><html> <head></head> <body> HELLO! $name,Welcome to velocity! </body> </html>
$name 為需要程式傳入的參數。
2. 以下為 velocityTest的代碼:
package velocity;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.text.MessageFormat;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;import org.apache.velocity.app.VelocityEngine;import org.joda.time.DateTime;public class VelocityTest {/** * @param args */public static void main(String[] args) {//得到VelocityEngineVelocityEngine ve = new VelocityEngine();//得到模板檔案 Template template = ve.getTemplate("/src/velocity/TaxReportXml.vm", "UTF-8"); VelocityContext context = new VelocityContext(); //傳入參數 context.put("name", "jacky"); try { //產生xmlFileWriter fileWriter = getFileWriter("velocity_test.xml");//調用merge方法傳入context template.merge(context, fileWriter); fileWriter.flush(); fileWriter.close();} catch (IOException e) {e.printStackTrace();} } private static FileWriter getFileWriter(String fileName) throws IOException { String fullPath = MessageFormat.format("{1}{0}{2}", File.separator, "d://", fileName); System.out.println("fileName = " + fullPath); File outputFile = new File(fullPath); return new FileWriter(outputFile); }}
看一下運行結果,在d:下的velocity_test.xml中:
<?xml version="1.0" encoding="utf-8"?><html> <head></head> <body> HELLO! jacky,Welcome to velocity! </body> </html>
參數已經傳到xml裡了,很簡單吧