一、Velocity是什么
Velocity是一个基于java的模板引擎。Velocity将Java代码从web页面中分离出来,使web站点在其生命周期中更具可维护性,并为Java Server pages (jsp)或PHP提供了一种可行的替代方案。
它可以用来从模板生成SQL、PostScript和XML。
Velocity组成结构分为App模块,Context模块,Runtime模块,RuntimeInstance模块。
二、快速开始
1.引入依赖
<!--Velocity-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
2.定义模板
在resource目录下创建一个HTML文件修改后缀名为.vm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello,${name}!
</body>
</html>
3.测试
@Test
public void test01() throws Exception {
//1.设置velocity资源加载器
Properties properties = new Properties();
//固定写法
properties.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//2.初始化velocity引擎
Velocity.init(properties);
//3.创建velocity容器
VelocityContext context = new VelocityContext();
context.put("name", "lisi");
//4.加载velocity模板文件
Template template = Velocity.getTemplate("vms/01-quickstart.vm", "UTF-8");
//5.合并数据到模板
FileWriter fw = new FileWriter("D:\\projectdemo\\java8\\src\\main\\resources\\html\\01-quickstart.html");
template.merge(context, fw);
//6.释放资源
fw.close();
}
三、语法
1、VTL是velocity提供的一种模板语言,分为四大类注释、非解析内容、引用。
a、注释
单行注释:#单行注释#
多行注释:#*多行注释*#
文档注释:#**文档注释*#
b、非解析内容: #[[非解析内容]]#
c、引用
1.变量引用
语法:$属性或者${属性}
$!属性或者$!{属性}:如果没有值就显示空字符
2.属性引用
$变量名.属性或者${变量名.属性}
$!变量名.属性或者$!{变量名.属性}:如果没有值就显示空字符
3.方法引用
$变量名.方法()
${变量名.方法()}
四、指令
1.流程控制
1)#set
#set($变量=值)
eg:#set($str="hello world ")
2)#if/#else if
#if(条件)
#else if(条件)
#end
3)#foreach
普通数组:
#foreach($item in $item)
$foreach.index----$item
$foreach.count----$item
[#break]
#end
对象集合:
#foreach($item in $item)
$item.对象属性
#end
map:
#foreach($entry in $map.entrySet())
$entry.key-----$entry.value
#end
2.引入资源
1)#include 引入外部资源,引入的资源不会被引擎解析
#include(resource)resource:可以为单引号或者双引号,也可以为$变量,内容为外部资源路径
2)#parse 引入外部资源,引入的资源会被引擎解析
#parse(resource)resource:可以为单引号或者双引号,也可以为$变量,内容为外部资源路径
3)#define 定义重用模块(不带参数)
#define($模块名称)
模块内容
#end
$模块名称调用
4)#evalute 动态计算出我们在字符串中使用的变量
#evalute("计算语句")
3.宏指令
定义重用模块(可以带参数)
#macro(宏名 [$arg])
……
#end
#宏名(参数)调用
五、代码生成器
1.定义vm文件
Controller.java.vm
package ${
package}.controller;
import ${
package}.domain.${
className};
import ${
package}.service.${
className}Service;
import org.springframework.beans.factory.annotation.Autowired;
import