溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Velocity模板引擎的簡單使用

發(fā)布時間:2020-08-11 22:26:13 來源:網(wǎng)絡(luò) 閱讀:6671 作者:pangfc 欄目:開發(fā)技術(shù)

一 簡介

Velocity 是一個基于 Java 的模板引擎,它允許任何人僅僅簡單的使用模板語言來引用由 Java 代碼定義的對象,從而實(shí)現(xiàn)界面和 Java 代碼的分離,使得界面設(shè)計(jì)人員可以和 Java 程序開發(fā)人員同步開發(fā)一個遵循 MVC 架構(gòu)的 web 站點(diǎn)。

二 一個簡單示例

(1)從官網(wǎng)下載最新的jar包,然后新建一個普通的Java工程,然后導(dǎo)入下載下來的zip文件中的jar包。當(dāng)然也可以使用我用過的jar包,鏈接:http://pan.baidu.com/s/1PXu5g

(2)新建一個包:cn.zifangsky,然后新建文件Hellovelocity.vm,里面的內(nèi)容如下:

#set($domain="http://www.zifangsky.cn")
whoami: $name

today is $date.
#foreach($i in $list)
$i
#end

website:$domain

(3)在同一個包下新建文件HelloVelocity.java,內(nèi)容如下:

package cn.zifangsky;

import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class HelloVelocity {
	public static void main(String[] args){
		//初始化引擎
		VelocityEngine vEngine = new VelocityEngine();
		vEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		vEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		
		vEngine.init();
		//讀取Hellovelocity.vm這個模板生成的Template這個類
		Template template = vEngine.getTemplate("cn/zifangsky/Hellovelocity.vm");
		VelocityContext context = new VelocityContext();
		
		context.put("name", "zifangsky");
		context.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		
		List<String> list = new ArrayList<String>();
		list.add("hello");
		list.add("velocity");
		context.put("list", list);
		
		StringWriter writer = new StringWriter();
		template.merge(context, writer);
		System.out.println(writer.toString());
	}
}

(4)輸出如下:

whoami: zifangsky

today is 2016-03-10 15:37:49.
hello
velocity

website:http://www.zifangsky.cn

實(shí)際上,這個模板引擎的工作原理還是比較容易理解的,就是先定義一系列的.vm模板,然后在Java文件中讀取這些模板文件將值傳進(jìn)去以此生成動態(tài)頁面



附:Velocity語法:


一、基本語法
 
1、”#”用來標(biāo)識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

2、”$”用來標(biāo)識一個對象(或理解為變量);如
 如:$i、$msg、$TagUtil.options(…)等。

3、”{}”用來明確標(biāo)識Velocity變量;
 比如在頁面中,頁面中有一個$someonename,此時,Velocity將把someonename作為變量名,若我們程序是想在someone這個變量的后面緊接著顯示name字符,則上面的標(biāo)簽應(yīng)該改成${someone}name。

4、”!”用來強(qiáng)制把不存在的變量顯示為空白。
 如當(dāng)頁面中包含$msg,如果msg對象有值,將顯示msg的值,如果不存在msg對象同,則在頁面中將顯示$msg字符。這是我們不希望的,為了把不存在的變量或變量值為null的對象顯示為空白,則只需要在變量名前加一個“!”號即可。
 如:$!msg
 
二、在EasyJWeb中的最佳實(shí)踐
 
    理論上你可以在EasyjWeb模板使用所有Velocity的腳本及功能,但我們不推薦你在界面模板中使用過多過復(fù)雜的腳本表達(dá)方式,在萬不得已的情況下,不要在界面模板中加入任何復(fù)雜的邏輯,更不要在界面模板中加入變量聲明、邏輯運(yùn)算符等等。 
在EasyJWeb中,我們提供了五條基本的模板腳本語句,基本上就能滿足所有應(yīng)用模板的要求。這四條模板語句很簡單,可以直接由界面設(shè)計(jì)人員來添加。在當(dāng)前很多EasyJWeb的應(yīng)用實(shí)踐中,我們看到,所有界面模板中歸納起來只有下面四種簡單模板腳本語句即可實(shí)現(xiàn):
1、$!obj  直接返回對象結(jié)果。
 如:在html標(biāo)簽中顯示java對象msg的值。<p>$!msg</p>
在html標(biāo)簽中顯示經(jīng)過HtmlUtil對象處理過后的msg對象的值  <p>$!HtmlUtil.doSomething($!msg)</p>

2、#if($!obj) #else #end 判斷語句
 如:在EasyJWeb各種開源應(yīng)用中,我們經(jīng)??吹降挠糜趶棾鎏崾拘畔sg的例子。
#if($msg)
 <script>
 alert(‘$!msg’);
 </script>
 #end
上面的腳本表示當(dāng)對象msg對象存在時,輸出<script>等后面的內(nèi)容。

3、#foreach( $info in $list) $info.someList #end  循環(huán)讀取集合list中的對象,并作相應(yīng)的處理。
 如:EasyJF開源論壇系統(tǒng)中論(0.3)壇首頁顯示熱門主題的html界面模板腳本:
#foreach( $info in $hotList1) 
 <a href=”/bbsdoc.ejf?easyJWebCommand=show&&cid=$!info.cid” target=”_blank”>$!info.title</a><br>
 #end 
上面的腳本表示循環(huán)遍歷hotList1集合中的對象,并輸出對象的相關(guān)內(nèi)容。

4、#macro(macroName)#end 腳本函數(shù)(宏)調(diào)用,不推薦在界面模板中大量使用。
 如:在使用EasyJWeb Tools快速生成的添刪改查示例中,可以點(diǎn)擊列表的標(biāo)題欄進(jìn)行升降排序顯示,這是我們在EasyJWeb應(yīng)用中經(jīng)常看到的一個排序狀態(tài)顯示的模板內(nèi)容。
 函數(shù)(宏)定義,一般放在最前面
#macro(orderPic $type)
 #if ($orderField.equals($type)) 
 <img src=”https://cache.yisu.com/upload/information/20200312/65/247712.jpg”> 
 #end
 #end
具體的調(diào)用如:<font color=”#FFFFFF”>頭銜#orderPic(“title”)</font> 

5、包含文件#inclue(“模板文件名”)或#parse(“模板文件名”)
主要用于處理具有相同內(nèi)容的頁面,比如每個網(wǎng)站的頂部或尾部內(nèi)容。
 使用方法,可以參考EasyJF開源Blog及EasyJF開源論壇中的應(yīng)用!
 如:#parse(“/blog/top.html”)或#include(“/blog/top.html”)
 parse與include的區(qū)別在于,若包含的文件中有Velocity腳本標(biāo)簽,將會進(jìn)一步解析,而include將原樣顯示。

三、關(guān)于#set的使用

在萬不得已的時候,不要在頁面視圖自己聲明Velocity腳本變量,也就是盡量少使用#set。有時候我們需要在頁面中顯示序號,而程序?qū)ο笾杏譀]有包含這個序號屬性同,可以自己定義。如在一個循環(huán)體系中,如下所示:
#set ($i=0)
 #foreach($info in $list)
序號:$i
 #set($i=$i+1)
 #end

四、Velocity腳本語法摘要
 
1、聲明:#set ($var=XXX)
左邊可以是以下的內(nèi)容
Variable reference 
 String literal 
 Property reference 
 Method reference 
 Number literal #set ($i=1) 
 ArrayList #set ($arr=[“yt1″,”t2”])
算術(shù)運(yùn)算符

2、注釋:
單行## XXX
多行#* xxx
 xxxx
 xxxxxxxxxxxx*#

 References 引用的類型
3、變量 Variables 
以 “$” 開頭,第一個字符必須為字母。character followed by a VTL Identifier. (a .. z or A .. Z).
變量可以包含的字符有以下內(nèi)容:
alphabetic (a .. z, A .. Z) 
 numeric (0 .. 9) 
 hyphen (“-“) 
 underscore (“_”) 

4、Properties 
 $Identifier.Identifier
 $user.name
 hashtable user中的的name值.類似:user.get(“name”)

5、Methods 
 object user.getName() = $user.getName()

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

 如
#set ($user=”csy”}
 ${user}name 
返回csyname

 $username
 $!username
 $與$!的區(qū)別
 當(dāng)找不到username的時候,$username返回字符串”$username”,而$!username返回空字符串”” 

7、雙引號 與 引號 
#set ($var=”helo”)
 test”$var” 返回testhello
 test’$var’ 返回test’$var’
可以通過設(shè)置 stringliterals.interpolate=false改變默認(rèn)處理方式

8、條件語句
#if( $foo ) 
 <strong>Velocity!</strong>
 #end
 #if($foo)
 #elseif()
 #else
 #end
當(dāng)$foo為null或?yàn)锽oolean對象的false值執(zhí)行.

9、邏輯運(yùn)算符:== && || !

10、循環(huán)語句#foreach($var in $arrays ) // 集合包含下面三種Vector, a Hashtable or an Array
 #end
 #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

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

12、包含文件 
#include( “one.gif”,”two.txt”,”three.htm” )

13、Parse導(dǎo)入腳本
#parse(“me.vm” )

14、#stop 停止執(zhí)行并返回 

15、定義宏Velocimacros ,相當(dāng)于函數(shù) 支持包含功能
#macro( d )
 <tr><td></td></tr>
 #end
調(diào)用 
#d()

16、帶參數(shù)的宏
#macro( tablerows $color $somelist )
 #foreach( $something in $somelist )
 <tr><td bgcolor=$color>$something</td></tr>
 #end
 #end

17、Range Operator 
 #foreach( $foo in [1..5] ) 
 
 

注:參考文章:http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/

語法部分轉(zhuǎn)載至:http://www.cnblogs.com/siye1982/archive/2007/11/14/959678.html

想繼續(xù)了解的話,也可以參考這篇文章:http://www.ablanxue.com/prone_314_1.html


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI