基本模式
當你在一個應用程序或者一個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 ) |
25 |
catch (
ParseErrorException pee ) |
29 |
catch (
MethodInvocationException mie ) |
37 |
StringWriter
sw = new StringWriter(); |
39 |
template.merge(
context, sw ); |
這是個基本的模式,它非常簡單,不是嗎?當你使用Velocity渲染一個模板的時候,通常會發生什麼。你可能不會完全像這樣寫代碼,所以我們提供幾個工具類幫助你寫代碼。然而, 無論如何,按照上面的序列使用Velocity,它向我們展示了臺前幕後發生了什麼。