721
阿裏雲
技術社區[雲棲]
Velocity官方指南-Velocity是如何工作的
基本模式
當你在一個應用程序或者一個servlet裏,或者在其他任何一個地方使用Velocity時,通常按照如下方式處理:
- 初始化Velocity。Velocity可以使用兩種模式,作為“單獨的運行時實例”的單例模式(在下麵的內容會介紹),你僅僅隻需要初始化一次。
- 創建一個Context對象(後麵會介紹這是什麼)。
- 把你的數據對象添加到Context(上下文)。
- 選擇一個模板。
- ‘合並’ 模板和你的數據輸出。
在代碼裏通過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;
|
11 |
VelocityContext context = new VelocityContext();
|
13 |
context.put( "name" , new String( "Velocity" ) );
|
15 |
Template template = null ;
|
19 |
template = Velocity.getTemplate( "mytemplate.vm" );
|
21 |
catch ( ResourceNotFoundException rnfe )
|
23 |
// couldn't find the template
|
25 |
catch ( ParseErrorException pee )
|
27 |
// syntax error: problem parsing the template
|
29 |
catch ( MethodInvocationException mie )
|
31 |
// something invoked in the template
|
37 |
StringWriter sw = new StringWriter();
|
39 |
template.merge( context, sw ); |
這是個基本的模式,它非常簡單,不是嗎?當你使用Velocity渲染一個模板的時候,通常會發生什麼。你可能不會完全像這樣寫代碼,所以我們提供幾個工具類幫助你寫代碼。然而, 無論如何,按照上麵的序列使用Velocity,它向我們展示了台前幕後發生了什麼。
最後更新:2017-05-22 16:37:33