package zoer;
import java.io.StringWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
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", "mason");
context.put("site", "Naughty 's");
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge(context, writer);
/* show the World */
System.out.println(writer.toString());
}
}
在項目根目錄下建立一個hellosite.vm,內容:
Hello $name! Welcome to $site world!
執行上面java代碼,則會產生響應的html代碼。這裡只是 簡單一實例。並不是web工程。
簡單看了一下velocity模板引擎,其優勢是,拋棄了jsp,雖然jsp是J2EE的一部分,但是J2EE並不一定使用jsp,也可以使用velocity等這類模板引擎,同樣可以實現MVC,將代碼邏輯和頁面展現分開。
ps:前面學習了Django架構之後,再來看velocity模板引擎,感覺他們的Template和使用方式是類似的。都極其簡單。