文章出處

velocityfreemaker、jstl并稱為java web開發三大標簽技術,而且velocity在codeplex上還有.net的移植版本NVelocity,(注:castle團隊在github上也維護了一個版本)對于使用異構技術的團隊(即要搞.NET又要搞JAVA),總是希望找一種通用的技術,兼容所有技術平臺,以便降低學習成本,無疑velocity是一種值得考慮的選擇。

一、與strtus2的集成

 1         <dependency>
 2             <groupId>org.apache.velocity</groupId>
 3             <artifactId>velocity</artifactId>
 4             <version>1.7</version>
 5         </dependency>
 6 
 7         <dependency>
 8             <groupId>org.apache.velocity</groupId>
 9             <artifactId>velocity-tools</artifactId>
10             <version>2.0</version>
11         </dependency>

pom.xml中加入這二項即可,其它不用刻意配置。struts2同時支持jstl(.jsp)、velocity(.vm)、freemaker(.ftl)三種模板。

 

二、定義變量

1   #set($awbpre='112')
2   #set($awbno='89089011')
3   #set($airwayBillNo=$awbpre+' - '+$awbno)
4   $awbpre - $awbno <br/>
5   $airwayBillNo

velocity的語法符號大概分二類,一類用#開頭,代表控制符號,#set表示定義變量,另一類用$開頭,通常用于顯示變量,上面的示例定義了三個變量:
awbpre 值為'112',awbno值為'89089011',airwayBillNo值為 '112 - 89089011'

第4,5二行輸出內容

 

三、遍歷數組

1   #set($list = ["CTU", "SHA", "LAX"])
2   #foreach ($item in $list)
3      $velocityCount . $item <br/>
4   #end

解釋:定義了一個數組,然后遍歷輸出,其中velocityCount為索引變量

 

四、遍歷HashTable

1   #foreach($key in $table.keySet())
2     $key -> $table.get($key)<br/>
3   #end


五、判斷是否為空

1       #if($null.isNull($orderList.orders) || $orderList.orders.size()==0)
2           訂單列表為空
3       #else
4           訂單列表:<br/>
5           #foreach ($order in $orderList.orders)
6               $velocityCount: $order.id / $order.clientName / $order.amount / $order.createTime<br/>
7           #end
8       #end

上面是判斷集合是否為空的,如果判斷單個對象是否為空,參考下面這樣:

 1     #if($(orderDto))
 2         訂單對象有值
 3     #else
 4         訂單對象為空
 5     #end
 6 
 7     #if(!$(orderDto))
 8         訂單對象為空
 9     #else
10         訂單對象有值
11     #end

 


六、宏示例

宏可以理解為“函數”,定義一個宏即相當于定義一個子函數,調用宏,即為調用子函數

 1     #macro(renderOrderList $orders)
 2         <table border="1">
 3           <tr>
 4               <th>Id</th>
 5               <th>ClientName</th>
 6               <th>Amount</th>
 7               <th>CreateTime</th>
 8           </tr>
 9           #foreach($o in $orders)
10             <tr><td>$o.id</td><td>$o.clientName</td><td>$o.amount</td><td>$o.createTime</td></tr>
11           #end
12         </table>
13     #end
14 
15     #renderOrderList($orderList.orders)


七、數值、日期格式化

1     $order.createTime<br/>
2     $date.year - $date.month - $date.day <br/>
3     $date.format('yyyy-MM-dd HH:mm:ss',$order.createTime,$locale)<br/>  
4     $date.format('MMMdd',$order.createTime,$locale)<br/>    
5     $convert.toLocale("en_US") <br/>
6     $date.format('MMM,dd',$order.createTime,$convert.toLocale("en_US"))<br/>
7     $date.format('yyyy-MM-dd',$order.createTime,$locale)<br/>
8     $order.amount<br/>
9     $number.format('0.00',$order.amount)<br/>
NumberTool中還有貨幣格式化的功能:$number.format("currency", $agentBillDto.feeTotal)

要使用格式化功能,需要加一點配置,struts.xml文件中加一行

<constant name="struts.velocity.toolboxlocation" value="WEB-INF/classes/toolbox.xml" />

然后在toolbox.xml中,參考下面的內容:

 1 <?xml version="1.0" encoding="UTF-8"?> 
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
 4     "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
 5 <toolbox>
 6     <tool>
 7         <key>number</key>
 8         <scope>application</scope>
 9         <class>org.apache.velocity.tools.generic.NumberTool</class>
10     </tool>
11     <tool>
12         <key>date</key>
13         <scope>application</scope>
14         <class>org.apache.velocity.tools.generic.DateTool</class>
15     </tool>
16     <tool>
17         <key>text</key>
18         <scope>request</scope>
19         <class>org.apache.velocity.tools.struts.MessageTool</class>
20     </tool>
21     <tool>
22         <key>convert</key>
23         <scope>application</scope>
24         <class>org.apache.velocity.tools.generic.ConversionTool</class>
25     </tool>
26 </toolbox>
View Code

這些XXXTool其實是一個很好的例子,因為velocity的vm文件里不能直接寫java代碼,如果我們想擴展一些常用方法,可以將一些常用方法寫成XXXTool工具類,然后在toolbox中注冊即可。

 

 

八、國際化

1  當前語言環境:$locale <br/>   
2  #stext("name=%{getText('appName')}")

雖然Velocity-Tools 2.0中提供了MessageTool,但是我一直沒嘗試成功,只能借助struts2本身的標簽來處理了。struts2中首先得定義國際化資源文件的BaseName

1 <constant name="struts.custom.i18n.resources" value="message"></constant>

然后在classPath目錄下,放二個文件message_zh_CN.properties、message_en_US.properties,里面放一個appName=XXX的內容,用#stext就能取到國際化的內容了

 

九、使用struts2標簽

雖然有了velocity基本上可以告別struts2的那一堆tags,但是如果懷念struts2里的標簽,也可以繼續使用,方法:以“#s”開頭就行了,參考下面的示例:

1 #stextarea ("label=Biography" "name=bio" "cols=20" "rows=3") <br/>
2 #sselect("label=Favourite Color" "list={'Red', 'Blue', 'Green'}" "name=favouriteColor" "emptyOption=true" "headerKey=None" "headerValue=None")    <br/> 

 

十、內建對象

1 $request<br/>
2 name = $request.getParameter("name")<br/>
3 $session<br/>

Velocity可以直接使用struts2的很多內置對象,比如Request、Session、Response,上面的示例演示了如何獲取 url請求參數

 

十一、include、parse實現布局模塊化

每個頁面,通常會有一些公用的頭、尾,可以用include或parse來包括其它vm文件(或txt/html文件),這二個的區別在于include只是簡單的把其它文件導入進來,不會執行任何vm語法的解析。而parse導入其它vm文件時,如果其它vm文件里有一些指令,比如定義變量,定義宏之類,parse會解析執行。

1 #parse("template/header.vm")
2 #include("template/footer.vm")

關于加載的路徑,這里要重點解釋一下,官方文檔上也講得不清不楚,Velocity支持二種路徑加載機制,按classPath或按filePath,默認是按classPath路徑加載,即:只要被包含的.vm文件在/WEB-INF/classes目錄下即可。上面的示例,將在/WEB-INF/classes/template目錄下,搜索header.vm、footer.vm這二個文件,如果找到就加載,否則出錯。

最后談下IDE以.vm的可視化支持問題,目前最新的eclipse上,暫無好用的插件(googlecode上的插件大多已經沒人維護了,與最新的eclipse不兼容),建議使用IntelliJ Idea,它對vm的可視化支持程度較好。

 

更詳細的用法,請參考下面官司文檔:

Velocity Engine 用戶指南

Velocity Engine 開發人員指南

Velocity Tools 用法概述


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()