2014-04-24 88 views
1

有人可以解釋一下,什麼是Apache Velocity? 它的用途是什麼?什麼是Apache Velocity?

很高興能提供一個例子。

在此先感謝。

+4

加油。 [Apache Velocity Engine網站](http://velocity.apache.org/engine/releases/velocity-1.7/index.html)(我想,你談論引擎)包含了一切。一個很好的解釋概述,一個用戶指南和一個例子,等等。 – Seelenvirtuose

+0

您剛剛使用了一個標籤,其中有相當多的關於這個主題的信息,在它的描述中:)點擊問題中的[tag:velocity]標籤來閱讀它。 – toniedzwiedz

+0

無法清楚地瞭解它。對這些有較少的經驗。這就是爲什麼張貼。不管怎麼說,還是要謝謝你。 – user3152555

回答

10

Apache Velocity是一個template engine。這意味着您可以將變量添加到上下文中,加載一個模板,其中引用了這些變量,並使用此模板呈現文本,其中將變量的引用替換爲變量的實際值。

它的目的是將代碼中的設計和靜態內容分開。以一個網站爲例。你不想在你的java代碼中創建HTML,是嗎?每次更改一些設計時,您都必須重新編譯您的應用程序,並且會用不必要的設計混亂來警告您的代碼。你更希望得到你的變量,無論是計算出來的,還是來自數據庫或其他任何東西,並讓設計人員創建一個HTML模板,在其中使用變量。

一些僞代碼,使其明確:

/* The user's name is "Foo" and he is of type "admin"*/ 
User user = getUserFromDatabase("Foo"); 

/* You would not add hard coded content in real world. 
* it is just to show how template engines work */ 
String message = "Hello,"; 

Velocity.init(); /* Initialises the Velocity engine */ 

VelocityContext ctx = new VerlocityContext(); 

/* the user object will be available under the name "user" in the template*/ 
ctx.put("user",user); 
/* message as "welcome" */ 
ctx.put("welcome",message); 

StringWriter writer = new StringWriter(); 

Velocity.mergeTemplate("myTemplate.vm", ctx, writer); 

System.out.println(writer); 

現在給出了一個名爲myTemplate.vm

文件
${welcome} ${user.name}! 
You are an ${user.type}. 

輸出將是:

Hello, Foo! 
You are an admin. 

現在讓我們假設平面文字應該是HTML。設計者將改變myTemplate.vm到

<html> 
<body> 
    <h1>${welcome} ${user.name}</h1> 
    <p>You are an ${user.type}</p> 
</body> 
</html> 

所以輸出將是一個HTML頁面沒有在Java代碼的單一變化。

所以使用類似速度的模板引擎(還有其他的,例如ThymeleafFreemarker)讓設計師做一個設計師的工作和程序員做一個程序員的工作與相互干擾最小。

+0

明白了。感謝您精確回答所有問題。 – user3152555

+0

謝謝。非常清楚。 –