当前位置:网站首页>模板引擎Velocity 基礎
模板引擎Velocity 基礎
2022-07-01 16:36:00 【一切總會歸於平淡】
目錄
1、velocity簡介
Velocity是一個基於Java的模板引擎,可以通過特定的語法獲取在java對象的數據 , 填充到模板中,從而實現界面和java代碼的分離 !

那 Velocity 有什麼應用場景呢?
- Web應用程序 : 作為為應用程序的視圖, 展示數據。
- 源代碼生成 : Velocity可用於基於模板生成Java源代碼。
- 自動電子郵件 : 網站注册 , 認證等的電子郵件模板。
- 網頁靜態化 : 基於velocity模板 , 生成靜態網頁。
組成結構:
模塊 | 描述 |
app | 主要封裝了一些接口 , 暴露給使用者使用。主要有兩個類,分別是Velocity(單例)和VelocityEngine。 |
Context | 主要封裝了模板渲染需要的變量 |
Runtime | 整個Velocity的核心模塊,Runtime模塊會將加載的模板解析成語法樹,Velocity調用mergeTemplate方法時會渲染整棵樹,並輸出最終的渲染結果。 |
RuntimeInstance | RuntimeInstance類為整個Velocity渲染提供了一個單例模式,拿到了這個實例就可以完成渲染過程了。 |
詳細介紹大家可以看官網,傳送門放這裏了:The Apache Velocity Project
2、 快速入門
這裏給大家簡單演示如何使用Velocity定義html 模板,然後將動態數據填充到模板中,最後形成一個完整的html 頁面。
首先我們創建一個項目,我就直接創建一個springBoot 項目了,大家可以根據自己的需求來。

創建好項目,我們引入velocity依賴。
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>我們在resources 目錄下創建模板文件。

模板文件內容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello , ${name} !
</body>
</html>模板創建好之後,我們到Test 類中,編寫java 代碼。

@Test
void contextLoads() throws IOException {
// 1、設置velocity資源加載器
Properties prop = new Properties();
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 2、初始化velocity引擎
Velocity.init(prop);
// 3、創建Velocity容器
VelocityContext context = new VelocityContext();
context.put("name", "一切總會歸於平淡");
// 4、加載Velocity模板
Template tpl = Velocity.getTemplate("vms/demo01.vm", "UTF-8");
// 5、合並數據到模板
FileWriter fw = new FileWriter("E:\\code\\Demo\\velocityDemo\\src\\main\\resources\\html\\demo01.html");
tpl.merge(context, fw);
// 6、釋放資源
fw.close();
}
輸出結果:

Velocity解决了如何在後臺程序和網頁之間傳遞數據的問題,後臺代碼和視圖之間相互獨立,一方的修改不影響另一方,他們之間是通過環境變量(Context)來實現的,網頁制作一方和後臺程序一方相互約定好對所傳遞變量的命名約定,比如上面程序例子中的 name變量,它們在網頁上就是$name 。
只要雙方約定好了變量名字,那麼雙方就可以獨立工作了。無論頁面如何變化,只要變量名不變,那麼後臺程序就無需改動,前臺網頁也可以任意由網頁制作人員修改。這就是Velocity的工作原理。
3、基礎語法
Velocity Template Language (VTL) , 是Velocity 中提供的一種模版語言 , 旨在提供最簡單和最幹淨的方法來將動態內容合並到網頁中。
簡單來說VTL可以將程序中的動態數展示到網頁中。
VTL的語句分為4大類:注釋 , 非解析內容 , 引用和指令。
3.1 VTL注釋
語法:
- 行注釋: ## 行注釋內容
- 塊注釋:#* 塊注釋內容1 塊注釋內容2 *#
- 文檔注釋:#** 文檔注釋內容1 文檔注釋內容2 *#
代碼演示:

3.2 非解析內容
什麼是非解析內容?
非解析內容就是不會被velocity 解析的內容,所寫的內容都會原樣輸出出來。
那這到底有什麼用呢?因為我們就算是直接在模板文件中書寫內容,它也會原樣直接顯示出來呀。
大家直接往下看。
語法:#[[ 非解析內容1 非解析內容2 ]]#
代碼演示 :

我們再把java代碼運行一下。


3.3 引用
引用語句就是對引擎上下文對象中的屬性進行操作。語法方面分為常規語法($屬性)和正規語法(${屬性})。
3.3.1 變量引用
語法 | 描述 |
$變量名 | 若上下文中沒有對應的變量,則輸出字符串"$變量名" |
${變量名} | 若上下文中沒有對應的變量,則輸出字符串"${變量名}" |
$!變量名 | 若上下文中沒有對應的變量,則輸出空字符串"" |
$!{變量名} | 若上下文中沒有對應的變量,則輸出空字符串"" |
代碼演示:

我們運行java 代碼看看執行效果:

3.3.2 屬性引用
語法 | 描述 |
$變量名.屬性 | 若上下文中沒有對應的變量,則輸出字符串"$變量名.屬性" |
${變量名.屬性} | 若上下文中沒有對應的變量,則輸出字符串"${變量名.屬性}" |
$!變量名.屬性 | 若上下文中沒有對應的變量,則輸出字符串"" |
$!{變量名.屬性} | 若上下文中沒有對應的變量,則輸出字符串"" |
代碼演示:

我們創建一個實體類。

我們修改一下測試類代碼。

我們運行一下代碼,看看執行效果。

3.3.3 方法引用
方法引用實際就是指方法調用操作,關注點返回值和參數 , 方法的返回值將輸出到最終結果中
語法 | 描述 |
$變量名.方法([入參1[, 入參2]*]?) | 若上下文中沒有對應的變量,則輸出字符串"$變量名.方法([入參1[, 入參2]*]?" |
${變量名.方法([入參1[, 入參2]*]?)} | 若上下文中沒有對應的變量,則輸出字符串"${變量名.方法([入參1[, 入參2]*]?)}" |
$!變量名.方法([入參1[, 入參2]*]?) | 若上下文中沒有對應的變量,則輸出字符串"" |
$!{變量名.方法([入參1[, 入參2]*]?)} | 若上下文中沒有對應的變量,則輸出字符串"" |
代碼演示:
我們修改一下java代碼。

然後修改 模板文件。

然後我們看看執行效果。

3.4 指令
方法引用實際就是指方法調用操作,關注點返回值和參數 , 方法的返回值將輸出到最終結果中
語法 | 描述 |
$變量名.方法([入參1[, 入參2]*]?) | 若上下文中沒有對應的變量,則輸出字符串"$變量名.方法([入參1[, 入參2]*]?" |
${變量名.方法([入參1[, 入參2]*]?)} | 若上下文中沒有對應的變量,則輸出字符串"${變量名.方法([入參1[, 入參2]*]?)}" |
$!變量名.方法([入參1[, 入參2]*]?) | 若上下文中沒有對應的變量,則輸出字符串"" |
$!{變量名.方法([入參1[, 入參2]*]?)} | 若上下文中沒有對應的變量,則輸出字符串"" |
代碼演示:
我們修改一下java代碼。

然後修改 模板文件。

然後我們看看執行效果。

3.4 指令
指令主要用於定義重用模塊、引入外部資源、流程控制。指令以 # 作為起始字符。
3.4.1 流程控制
指令 | 語法 | 描述 |
#set | #set($變量 = 值) | 在頁面中聲明定義變量 |
#if/#elseif/#else | 下面演示 | 進行邏輯判斷 |
#foreach | 下面演示 | 遍曆循環數組或者集合 |
1、#set

看看執行效果:

2、#if/#elseif/#else

我們看看執行效果。

3、#foreach

我們看看生成效果。

內置屬性:
$foreach.index | 獲取遍曆的索引 , 從0開始 |
$foreach.count | 獲取遍曆的次數 , 從1開始 |
3.4.2 引入資源
指令 | 描述 |
#include | 引入外部資源 , 引入的資源不會被引擎所解析 |
#parse | 引入外部資源 , 引入的資源將被引擎所解析 |
#define | 定義重用模塊(不帶參數) |
evaluate | 動態計算 , 動態計算可以讓我們在字符串中使用變量 |
1、#include
我們新建一個模板文件。

、
然後我們在 demo01.vm 中引入。

我們來看看執行效果

我們可以看到 ${now }並未被解析,這是大家要注意的。
2、#parse

我們看看執行的效果。

我們可以看到解析了。
3、#define

效果:

4、#evaluate

效果:

3.4.3 宏指令
作用 : 定義重用模塊(可帶參數)
定義語法:
#macro(宏名 [$arg]?)
.....
#end調用語法:
#宏名([$arg]?)演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
#set($userList = [
{"name":"一切總會歸於平淡","sex":"男","age":"22"}
])
<h1>定義宏</h1> #macro(table $list)
<table border="1px">
<tr>
<td>編號</td>
<td>用戶名</td>
<td>密碼</td>
<td>郵箱</td>
<td>年齡</td>
<td>操作</td>
</tr>
#foreach($item in $list)
<tr>
<td>${foreach.count}</td>
<td>${item.name}</td>
<td>${item.sex}</td>
<td>${item.age}</td>
</tr>
#end
</table>
#end
<h1>調用宏</h1>
#table($userList)
</body>
</html>效果:

边栏推荐
- [nodemon] app crashed - waiting for file changes before starting... resolvent
- Comment utiliser le langage MySQL pour les appareils de ligne et de ligne?
- How long will it take to achieve digital immortality? Metacosmic holographic human avatar 8i
- How to write good code - Defensive Programming Guide
- Vscode find and replace the data of all files in a folder
- How to optimize repeated if err in go language= Nil template code?
- Tutorial on the principle and application of database system (005) -- Yum offline installation of MySQL 5.7 (Linux Environment)
- Stegano in the world of attack and defense
- Preliminary study on golang crawler framework
- [daily news]what happened to the corresponding author of latex
猜你喜欢

数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)

部门来了个拿25k出来的00后测试卷王,老油条表示真干不过,已被...

The Department came to a Post-00 test paper king who took out 25K. The veteran said it was really dry, but it had been

数据库系统原理与应用教程(001)—— MySQL 安装与配置:MySQL 软件的安装(windows 环境)

游戏行业安全选择游戏盾,效果怎么样?

嗨 FUN 一夏,与 StarRocks 一起玩转 SQL Planner!

Do280 management application deployment - pod scheduling control

Im instant messaging develops a message delivery scheme for 10000 people

How to maintain the laptop battery

Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!
随机推荐
Principle of motion capture system
Idea start command line is too long problem handling
Guide for high-end programmers to fish at work
vim用户自动命令示例
怎么用MySQL语言进行行列装置?
Red team Chapter 8: blind guess the difficult utilization process of the package to upload vulnerabilities
IM即時通訊開發實現心跳保活遇到的問題
VMware 虛擬機啟動時出現故障:VMware Workstation 與 Hyper-v 不兼容...
动作捕捉系统用于苹果采摘机器人
Tutorial on the principle and application of database system (001) -- MySQL installation and configuration: installation of MySQL software (Windows Environment)
[nodemon] app crashed - waiting for file changes before starting...解决方法
接口测试框架中的鉴权处理
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
[daily news]what happened to the corresponding author of latex
Tutorial on the principle and application of database system (003) -- MySQL installation and configuration: manually configure MySQL (Windows Environment)
Zabbix2.2监控之系统及应用日志监控报警
How to maintain the laptop battery
Défaillance lors du démarrage de la machine virtuelle VMware: le poste de travail VMware n'est pas compatible avec hyper - V...
How long will it take to achieve digital immortality? Metacosmic holographic human avatar 8i
Use Tencent cloud to build a map bed service