Velocity官方指南-Velocity是如何工作的

基本模式

當你在一個應用程序或者一個servlet裏,或者在其他任何一個地方使用Velocity時,通常按照如下方式處理:

  1. 初始化Velocity。Velocity可以使用兩種模式,作爲“單獨的運行時實例”的單例模式(在下面的內容會介紹),你僅僅只需要初始化一次。
  2. 創建一個Context對象(後面會介紹這是什麼)。
  3. 把你的數據對象添加到Context(上下文)。
  4. 選擇一個模板。
  5. ‘合併’ 模板和你的數據輸出。

在代碼裏通過org.apache.velocity.app.Velocity類使用單例模式,代碼如下:

01 import java.io.StringWriter;
02 import org.apache.velocity.VelocityContext;
03 import org.apache.velocity.Template;
04 import org.apache.velocity.app.Velocity;
05 import org.apache.velocity.exception.ResourceNotFoundException;
06 import org.apache.velocity.exception.ParseErrorException;
07 import org.apache.velocity.exception.MethodInvocationException;
08  
09 Velocity.init();
10  
11 VelocityContext context = new VelocityContext();
12  
13 context.put( "name"new String("Velocity") );
14  
15 Template template = null;
16  
17 try
18 {
19    template = Velocity.getTemplate("mytemplate.vm");
20 }
21 catch( ResourceNotFoundException rnfe )
22 {
23    // couldn't find the template
24 }
25 catch( ParseErrorException pee )
26 {
27   // syntax error: problem parsing the template
28 }
29 catch( MethodInvocationException mie )
30 {
31   // something invoked in the template
32   // threw an exception
33 }
34 catch( Exception e )
35 {}
36  
37 StringWriter sw = new StringWriter();
38  
39 template.merge( context, sw );

這是個基本的模式,它非常簡單,不是嗎?當你使用Velocity渲染一個模板的時候,通常會發生什麼。你可能不會完全像這樣寫代碼,所以我們提供幾個工具類幫助你寫代碼。然而, 無論如何,按照上面的序列使用Velocity,它向我們展示了臺前幕後發生了什麼。

原創文章,轉載請註明: 轉載自併發編程網 – ifeve.com

發佈了167 篇原創文章 · 獲贊 1053 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章