閱讀918 返回首頁    go 阿裏雲 go 技術社區[雲棲]


采用字符串作為模板內容的 Velocity簡單實例。

package com.test.velocity;

import java.io.StringWriter;
import java.util.Date;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class HelloVelocity {

 /**
  * @param args
  */
 public static void main(String[] args) throws Exception {

  // 初始化並取得Velocity引擎
  VelocityEngine ve = new VelocityEngine();
  ve.init();

  // 取得velocity的模版內容, 模板內容來自字符傳

  String content = "";
  content += "Welcome  $name  to Javayou.com! ";
  content += " today is  $date.";

  // 取得velocity的上下文context
  VelocityContext context = new VelocityContext();

  // 把數據填入上下文
  context.put("name", "javaboy2012");

  context.put("date", (new Date()).toString());

  // 輸出流
  StringWriter writer = new StringWriter();

  // 轉換輸出

  ve.evaluate(context, writer, "", content); // 關鍵方法

  System.out.println(writer.toString());

 }

}

最後更新:2017-04-02 16:48:12

  上一篇:go C# 使用HttpWebRequest用Post提交MultiPart數據
  下一篇:go 關於模板語言Velocity的簡單例子