当前位置:网站首页>Template engine velocity Foundation
Template engine velocity Foundation
2022-07-01 16:39:00 【Everything will always return to plain】
Catalog
1、velocity brief introduction
Velocity It's based on Java Template engine for , It can be obtained through specific syntax in java Object's data , Fill to template , So as to realize the interface and function java Code separation !

that Velocity What are the application scenarios ?
- Web Applications : As a view for the application , Display data .
- Source code generation : Velocity Can be used for template based generation Java Source code .
- Automatic email : Website registration , E-mail template for authentication, etc .
- Page static : be based on velocity Templates , Generate static web page .
Make up the structure :
modular | describe |
app | It mainly encapsulates some interfaces , Exposed to the user for use . There are two main categories , Namely Velocity( Single case ) and VelocityEngine. |
Context | It mainly encapsulates the variables needed for template rendering |
Runtime | Whole Velocity Core module ,Runtime The module will parse the loaded template into the idiom tree ,Velocity call mergeTemplate Method will render the whole tree , And output the final rendering result . |
RuntimeInstance | RuntimeInstance Class is the whole Velocity Rendering provides a singleton mode , With this example, you can complete the rendering process . |
For a detailed introduction, you can see the official website , The portal is here :The Apache Velocity Project
2、 Quick start
Here is a simple demonstration of how to use Velocity Definition html Templates , Then fill the dynamic data into the template , Finally, a complete html page .
First we create a project , I'll just create one springBoot Project , You can do it according to your own needs .
Create a good project , We introduce velocity rely on .
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
We are resources Create template file under directory .
Template file content
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello , ${name} !
</body>
</html>
After the template is created , We went to the Test Class , To write java Code .
@Test
void contextLoads() throws IOException {
// 1、 Set up velocity Resource loader
Properties prop = new Properties();
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
// 2、 initialization velocity engine
Velocity.init(prop);
// 3、 establish Velocity Containers
VelocityContext context = new VelocityContext();
context.put("name", " Everything will always return to plain ");
// 4、 load Velocity Templates
Template tpl = Velocity.getTemplate("vms/demo01.vm", "UTF-8");
// 5、 Merge data into template
FileWriter fw = new FileWriter("E:\\code\\Demo\\velocityDemo\\src\\main\\resources\\html\\demo01.html");
tpl.merge(context, fw);
// 6、 Release resources
fw.close();
}
Output results :
Velocity It solves the problem of how to transfer data between the background program and the web page , Background code and views are independent of each other , The modification of one party shall not affect the other party , Between them is through environment variables (Context) To achieve , The web page maker and the background program mutually agree on the naming convention of the transmitted variables , For example, in the above program example name Variable , They are on the web $name .
As long as both parties agree on the variable name , Then both sides can work independently . No matter how the page changes , As long as the variable name remains unchanged , Then the background program does not need to be changed , The front page can also be modified by the web page maker at will . This is it. Velocity How it works .
3、 Basic grammar
Velocity Template Language (VTL) , yes Velocity A template language provided in , It aims to provide the simplest and cleanest way to merge dynamic content into web pages .
Simply speaking VTL The dynamic number in the program can be displayed in the web page .
VTL The statements of are divided into 4 Categories: : notes , Non parsed content , References and instructions .
3.1 VTL notes
grammar :
- Line notes : ## Line comment content
- Block annotation :#* Block comment content 1 Block comment content 2 *#
- Documentation Comments :#** The content of the document notes 1 The content of the document notes 2 *#
Code demonstration :
3.2 Non parsed content
What is non analytic content ?
Non parsed content will not be velocity The content of the analysis , What you write will be output as is .
What's the use of this ? Because even if we write content directly in the template file , It will also be directly displayed as it is .
Let's look down directly .
grammar :#[[ Non parsed content 1 Non parsed content 2 ]]#
Code demonstration :
Let's put java Run the code .
3.3 quote
The reference statement is to operate the attributes in the engine context object . Grammar is divided into regular grammar ($ attribute ) And formal grammar (${ attribute }).
3.3.1 Variable references
grammar | describe |
$ Variable name | If there is no corresponding variable in the context , Then the output string "$ Variable name " |
${ Variable name } | If there is no corresponding variable in the context , Then the output string "${ Variable name }" |
$! Variable name | If there is no corresponding variable in the context , Then output an empty string "" |
$!{ Variable name } | If there is no corresponding variable in the context , Then output an empty string "" |
Code demonstration :
We run java Look at the execution effect of the code :
3.3.2 Property reference
grammar | describe |
$ Variable name . attribute | If there is no corresponding variable in the context , Then the output string "$ Variable name . attribute " |
${ Variable name . attribute } | If there is no corresponding variable in the context , Then the output string "${ Variable name . attribute }" |
$! Variable name . attribute | If there is no corresponding variable in the context , Then the output string "" |
$!{ Variable name . attribute } | If there is no corresponding variable in the context , Then the output string "" |
Code demonstration :
Let's create an entity class .
Let's modify the test class code .
Let's run the code , Look at the execution .
3.3.3 Method reference
Method reference actually refers to method call operation , concerns Return value and Parameters , The return value of the method will be output to the final result
grammar | describe |
$ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?) | If there is no corresponding variable in the context , Then the output string "$ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?" |
${ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?)} | If there is no corresponding variable in the context , Then the output string "${ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?)}" |
$! Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?) | If there is no corresponding variable in the context , Then the output string "" |
$!{ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?)} | If there is no corresponding variable in the context , Then the output string "" |
Code demonstration :
So let's revise that java Code .
And then modify Template file .
Then let's see the implementation effect .
3.4 Instructions
Method reference actually refers to method call operation , concerns Return value and Parameters , The return value of the method will be output to the final result
grammar | describe |
$ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?) | If there is no corresponding variable in the context , Then the output string "$ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?" |
${ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?)} | If there is no corresponding variable in the context , Then the output string "${ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?)}" |
$! Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?) | If there is no corresponding variable in the context , Then the output string "" |
$!{ Variable name . Method ([ Enter the reference 1[, Enter the reference 2]*]?)} | If there is no corresponding variable in the context , Then the output string "" |
Code demonstration :
So let's revise that java Code .
And then modify Template file .
Then let's see the implementation effect .
3.4 Instructions
Instructions are mainly used to define reusable modules 、 Bring in external resources 、 Process control . Instruction to # As the starting character .
3.4.1 Process control
Instructions | grammar | describe |
#set | #set($ Variable = value ) | Declare and define variables in the page |
#if/#elseif/#else | The following demonstration | Make logical judgments |
#foreach | The following demonstration | Traverse a circular array or collection |
1、#set
Look at the execution :
2、#if/#elseif/#else
Let's see the implementation effect .
3、#foreach
Let's look at the generation effect .
Built in properties :
$foreach.index | Get the traversal index , from 0 Start |
$foreach.count | Get the number of iterations , from 1 Start |
3.4.2 Introduce resources
Instructions | describe |
#include | Bring in external resources , The introduced resources will not be parsed by the engine |
#parse | Bring in external resources , The introduced resources will be parsed by the engine |
#define | Define reuse modules ( With no arguments ) |
evaluate | Dynamic computing , Dynamic computation allows us to use variables in strings |
1、#include
Let's create a new template file .
、
And then we were in demo01.vm Introduction in .
Let's see how it works
We can see ${now } Not resolved , This is what we should pay attention to .
2、#parse
Let's see the effect of implementation .
We can see the parsing .
3、#define
effect :
4、#evaluate
effect :
3.4.3 Macro instructions
effect : Define reuse modules ( With parameters )
Definition grammar :
#macro( Macro name [$arg]?)
.....
#end
Call syntax :
# Macro name ([$arg]?)
demonstration :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
#set($userList = [
{"name":" Everything will always return to plain ","sex":" male ","age":"22"}
])
<h1> Defining macro </h1> #macro(table $list)
<table border="1px">
<tr>
<td> Number </td>
<td> user name </td>
<td> password </td>
<td> mailbox </td>
<td> Age </td>
<td> operation </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> Call the macro </h1>
#table($userList)
</body>
</html>
effect :
边栏推荐
- Germany if was crowned with many awards. How strong is this pair of headphones? In depth evaluation of yinpo GTW 270 hybrid
- Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
- 数据库系统原理与应用教程(001)—— MySQL 安装与配置:MySQL 软件的安装(windows 环境)
- VMware virtual machine failed during startup: VMware Workstation is incompatible with hyper-v
- Pico, do you want to save or bring consumer VR?
- How does go use symmetric encryption?
- 【Kotlin】高阶函数介绍
- 红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
- What are the differences between PHP and DW
- Zabbix2.2 monitoring system and application log monitoring alarm
猜你喜欢
[nodemon] app crashed - waiting for file changes before starting... resolvent
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
Learn selenium to simulate mouse operation, and you can be lazy a little bit
Installation and use of sqoop
毕业后5年,我成为了年薪30w+的测试开发工程师
Huawei issued hcsp-solution-5g security talent certification to help build 5g security talent ecosystem
VMware virtual machine failed during startup: VMware Workstation is incompatible with hyper-v
Bugku's file contains
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting
VMware 虛擬機啟動時出現故障:VMware Workstation 與 Hyper-v 不兼容...
随机推荐
【Hot100】20. Valid parentheses
Tutorial on the principle and application of database system (002) -- MySQL installation and configuration: MySQL software uninstallation (Windows Environment)
Principle of SSM framework
[daily news]what happened to the corresponding author of latex
红队第8篇:盲猜包体对上传漏洞的艰难利用过程
PostgreSQL 存储结构浅析
Preliminary study on golang crawler framework
數據庫系統原理與應用教程(006)—— 編譯安裝 MySQL5.7(Linux 環境)
复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
Is the programmer's career really short?
[jetsonnano] [tutorial] [introductory series] [III] build tensorflow environment
从大湾区“1小时生活圈”看我国智慧交通建设
Tutorial on principles and applications of database system (006) -- compiling and installing MySQL 5.7 (Linux Environment)
红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
VMware 虛擬機啟動時出現故障:VMware Workstation 與 Hyper-v 不兼容...
Talking from mlperf: how to lead the next wave of AI accelerator
Go language source level debugger delve
普通二本,去过阿里外包,到现在年薪40W+的高级测试工程师,我的两年转行心酸经历...
Buuctf gold III
P2592 [ZJOI2008]生日聚会(dp)