Velocity 是如何工作的呢? 雖然大多 Velocity 的應用都是基于 Servlet 的網頁制作。但是為了說明 Velocity 的使用,我決定采用更通用的 Java application 來說明它的工作原理。
似乎所有語言教學的開頭都是采用 HelloWorld 來作為第一個程序的示例。這里也不例外。
任何 Velocity 的應用都包括兩個方面:
第一是: 模板制作,在我們這個例子中就是 hellosite.vm:
它的內容如下(雖然不是以 HTML 為主,但是這很容易改成一個 html 的頁面)
Hello $name! Welcome to $site world!
第二是 Java 程序部分:
下面是 Java 代碼
import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class HelloWorld
{
public static void main( String[] args )
throws Exception
{
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.init();
/* next, get the Template */
Template t = ve.getTemplate( "hellosite.vm" );
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "Eiffel Qiu");
context.put("site", "http://www.eiffelqiu.com");
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );
}
}
將兩個文件放在同一個目錄下,編譯運行,結果是:
Hello Eiffel Qiu! Welcome to http://www.eiffelqiu.com world
為了保證運行順利,請從 Velocity 的網站 http://jakarta.apache.org/velocity/ 上下載 Velocity 的運行包,將其中的 Velocity Jar 包的路徑放在系統的 Classpath 中,這樣就可以編譯和運行以上的程序了。
出處:牧羊人手記