1. 程式人生 > >Velocity 語法及其在springMVC中的配置

Velocity 語法及其在springMVC中的配置

整合文章中有幾處問題:

  1. xml中配置的vm檢視解析器,應該按照本文的配置來。
  2. spring的版本,使用3.1.1.RELEASE,mabatis的版本,建議使用3.1.1,mybatis-spring,建議使用1.1.1。

Velocity是一個基於Java的模板引擎(template engine),它允許任何人僅僅簡單的使用模板語言(template language)來引用由java程式碼定義的物件。作為一個比較完善的模板引擎,Velocity的功能是比較強大的,但強大的同時也增加了應用複雜性。

一、基本語法

1、”#”用來標識Velocity的指令碼語句,包括#set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro等; 
如:

#if($info.imgs)  
<img src="$info.imgs" border=0>  
#else  
<img src="noPhoto.jpg">  
#end  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

2、”$“用來標識一個物件(或理解為變數);如 
如:$i、$msg、$TagUtil.options(...)等。

3、”{}”用來明確標識Velocity變數; 
比如在頁面中,頁面中有一個$someonename,此時,Velocity將把someonename作為變數名,若我們程式是想在someone這個變數的後面緊接著顯示name字元,則上面的標籤應該改成${someone}name

4、”!”用來強制把不存在的變數顯示為空白。 
如當頁面中包含$msg,如果msg物件有值,將顯示msg的值,如果不存在msg物件同,則在頁面中將顯示$msg字元。這是我們不希望的,為了把不存在的變數或變數值為null的物件顯示為空白,則只需要在變數名前加一個“!”號即可。 
如:$!msg 
我們提供了五條基本的模板指令碼語句,基本上就能滿足所有應用模板的要求。這四條模板語句很簡單,可以直接由介面設計人員來新增。在當前很多EasyJWeb的應用實踐中,我們看到,所有介面模板中歸納起來只有下面四種簡單模板指令碼語句即可實現: 
   1、$!obj  直接返回物件結果。 
   如:在html標籤中顯示java物件msg的值。<p>$!msg</p>

 
  在html標籤中顯示經過HtmlUtil物件處理過後的msg物件的值  

<p>$!HtmlUtil.doSomething($!msg)</p>  
  • 1
  • 1

  2、#if($!obj) #else #end 判斷語句 
   如:在EasyJWeb各種開源應用中,我們經常看到的用於彈出提示資訊msg的例子。 
  

#if($msg)  
<script>  
alert('$!msg');  
</script>  
#end  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

上面的指令碼表示當物件msg物件存在時,輸出<script>等後面的內容。

  3、#foreach( $info in $list) $info.someList #end  迴圈讀取集合list中的物件,並作相應的處理。 
   如:EasyJF開源論壇系統中論(0.3)壇首頁顯示熱門主題的html介面模板指令碼: 
 

#foreach( $info in $hotList1)  
    <a href="/bbsdoc.ejf?easyJWebCommand=show&&cid=$!info.cid" target="_blank">$!info.title</a><br>  
#end  
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

   上面的指令碼表示迴圈遍歷hotList1集合中的物件,並輸出物件的相關內容。 
   
   4、#macro(macroName)#end 指令碼函式(巨集)呼叫,不推薦在介面模板中大量使用。 
   如:在使用EasyJWeb Tools快速生成的添刪改查示例中,可以點選列表的標題欄進行升降排序顯示,這是我們在EasyJWeb應用中經常看到的一個排序狀態顯示的模板內容。 
   函式(巨集)定義,一般放在最前面 
  

#macro(orderPic $type)  
    #if ($orderField.equals($type))  
        <img src="/images/ico/${orderType}.gif">  
    #end  
#end  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

具體的呼叫如:<font color="#FFFFFF">頭銜#orderPic("title")</font>

  5、包含檔案#inclue("模板檔名")#parse("模板檔名") 
  主要用於處理具有相同內容的頁面,比如每個網站的頂部或尾部內容。 
  使用方法,可以參考EasyJF開源Blog及EasyJF開源論壇中的應用! 
  如:#parse("/blog/top.html")#include("/blog/top.html") 
  parse與include的區別在於,若包含的檔案中有Velocity指令碼標籤,將會進一步解析,而include將原樣顯示。

關於#set的使用

  在萬不得已的時候,不要在頁面檢視自己宣告Velocity指令碼變數,也就是儘量少使用#set。有時候我們需要在頁面中顯示序號,而程式物件中又沒有包含這個序號屬性同,可以自己定義。如在一個迴圈體系中,如下所示: 
  

#set ($i=0)  
  #foreach($info in $list)  
      序號:$i  
  #set($i=$i+1)  
#end  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

Velocity指令碼語法摘要

1、宣告:#set ($var=XXX) 
  左邊可以是以下的內容 
  

   Variable reference  
  String literal  
  Property reference  
  Method reference  
  Number literal #set ($i=1)  
  ArrayList #set ($arr=["yt1","t2"])  
  算術運算子
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2、註釋:

  單行## XXX  
  多行#* xxx  
  xxxx  
  xxxxxxxxxxxx*#  
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

  References 引用的型別 
3、變數 Variables 
  以 “$” 開頭,第一個字元必須為字母。character followed by a VTL Identifier. (a .. z or A .. Z). 
  變數可以包含的字元有以下內容: 
  

alphabetic (a .. z, A .. Z)  
  numeric (0 .. 9)  
  hyphen ("-")  
  underscore ("_")  
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

4、Properties 
  

$Identifier.Identifier  
  $user.name  
  hashtable user中的的name值.類似:user.get("name")  
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

5、Methods 
  

object user.getName() = $user.getName()  
  • 1
  • 1

6、Formal Reference Notation 
  用{}把變數名跟字串分開

  如 
  

#set ($user="csy"}  
  ${user}name  
  • 1
  • 2
  • 1
  • 2

  返回csyname

  $username  
  $!username 
  • 1
  • 2
  • 1
  • 2

  $$!的區別 
  當找不到username的時候,$username返回字串”$username“,而$!username返回空字串""

7、雙引號 與 引號 
 

   #set ($var="helo")  
  test"$var" 返回testhello  
  test'$var' 返回test'$var' 
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

  可以通過設定 stringliterals.interpolate=false改變預設處理方式

8、條件語句 
  

#if( $foo )  
   <strong>Velocity!</strong>  
#end  
#if($foo)  
#elseif()  
  #else  
#end  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

  當$foo為null或為Boolean物件的false值執行.

9、邏輯運算子:== && || !

10、迴圈語句#foreach($var in $arrays ) // 集合包含下面三種Vector, a Hashtable or an Array

  #foreach( $product in $allProducts )  
   <li>$product</li>  
  #end  

  #foreach( $key in $allProducts.keySet() )  
   <li>Key: $key -> Value: $allProducts.get($key)</li>  
  #end  

  #foreach( $customer in $customerList )  
   <tr><td>$velocityCount</td><td>$customer.Name</td></tr>  
  #end  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

11、velocityCount變數在配置檔案中定義 
  

   # Default name of the loop counter  
  # variable reference.  
  directive.foreach.counter.name = velocityCount  
  # Default starting value of the loop  
  # counter variable reference.  
  directive.foreach.counter.initial.value = 1  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

12、包含檔案 
 

 #include( "one.gif","two.txt","three.htm" )  
  • 1
  • 1

13、Parse匯入指令碼 
  

#parse("me.vm" )  
  • 1
  • 1

14、#stop 停止執行並返回

15、定義巨集Velocimacros ,相當於函式 支援包含功能 
  

定義:
    #macro( d )  
   <tr><td></td></tr>  
  #end  
呼叫  
  #d() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

16、帶引數的巨集 
  

#macro( tablerows $color $somelist )  
  #foreach( $something in $somelist )  
   <tr><td bgcolor=$color>$something</td></tr>  
  #end  
#end  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

17、Range Operator 
  

#foreach( $foo in [1..5] )  
  • 1
  • 1

三 Spring MVC 中 Volecity 的設定

<!-- 配置vm檢視解析器 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.velocity.VelocityLayoutView"/>
        <property name="toolboxConfigLocation" value="/WEB-INF/classes/toolbox.xml"/> 
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="prefix" value=""/>
        <property name="suffix" value=".vm" />
        <property name="layoutUrl" value="layout/default.vm"></property>
        <property name="layoutKey" value="layout"></property>  
        <property name="exposeSpringMacroHelpers" value="true" />
        <property name="screenContentKey" value="screen_content" />
        <property name="exposeRequestAttributes" value="true" /><!-- if open request Attributes-->
        <property name="requestContextAttribute" value="rc"/><!-- request Attribute name-->
        <property name="dateToolAttribute"><value>dateTool</value></property>
        <property name="numberToolAttribute"><value>numberTool</value></property>
    </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

解釋: 
配置layoutUrl設定系統預設的模板路徑, layoutKey設定模板檔案鍵值,設定該值後就可以在vm檔案中使用該鍵值設定模板路徑,screenContentKey表示指定vm檔案顯示位置 
通過以上配置後普通頁面velocity會自動套用layout/default.vm模板 
如果登入頁面需套用自己獨特的模板則如下 
可以在登入頁面中新增:#set($layout="login_layout.vm")則登入頁面將套用”login_layout.vm”模板

<!-- 配置velocity引擎 -->
    <bean id="velocityConfigurer"
        class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath" value="/WEB-INF/templates/" /><!-- 模板存放的路徑 -->
        <property name="configLocation" value="classpath:velocity.properties" />
    </bean>

    <!-- 配置檢視的顯示 -->
    <bean id="ViewResolver"
    class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="prefix" value="/" /><!-- 檢視檔案的字首,即存放的路徑 -->
        <property name="suffix" value=".vm" /><!-- 檢視檔案的字尾名 -->
        <property name="toolboxConfigLocation" value="/WEB-INF/tools.xml" /><!--toolbox配置檔案路徑-->
        <property name="dateToolAttribute" value="date" /><!--日期函式名稱-->
        <property name="numberToolAttribute" value="number" /><!--數字函式名稱-->
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="exposeSpringMacroHelpers" value="true" /><!--是否使用spring對巨集定義的支援-->
        <property name="exposeRequestAttributes" value="true" /><!--是否開放request屬性-->
        <property name="requestContextAttribute" value="rc"/><!--request屬性引用名稱-->
        <property name="layoutUrl" value="layout/default.vm"/><!--指定layout檔案-->
    </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21