Velocity的使用
  TEZNKK3IfmPf 2023年11月14日 24 0

二八佳人体似酥,腰间仗剑斩愚夫。虽然不见人头落,暗里教君骨髓枯。

上一章简单介绍了FreeMarker的使用,如果没有看过,​​请观看上一章​​

Velocity 的官方网址: ​​https://velocity.apache.org/​​

与 FreeMarker 一样,也是模板引擎。

二. Java 使用Velocity

二.一 前期准备

创建一个 Maven 项目, 在 pom.xml 中添加 依赖

<dependencies>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<!--测试junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

Velocity的使用

二.二 模板开发

这儿不与 Web 进行关联,不采用页面展示, 采用控制台输出。

二.二.一 基本信息展示

二.二.一.一 基本信息模板 vm

创建 basic.vm 文件

## Velocity Hello World
<html>
<body>
## followed by
Hello,我是你们的老朋友,
## 放置读取的信息.
#set($name="周小欢")
#*
如果同时设置的话,以 #set 为主。
*#
Hello,介绍一个新的朋友,
## 放置普通的对象信息
的年龄是
</body>
</html>

有基本的信息 name, 有对象的信息 info.name 和 info.age

可以通过 set 设置一个新的属性。

二.二.一.二 基本信息开发
@Test
public void basicFill() throws Exception{
//1. 初始化模板引擎
VelocityEngine ve=new VelocityEngine();
//2. 设置相应的属性信息
ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
//3. 进行初始化
ve.init();
//4.获取模板文件
Template template=ve.getTemplate("basic.vm","utf-8");
//5.设置变量
VelocityContext root=new VelocityContext();
root.put("name","岳泽霖");
Map<String,Object> info=new HashMap<>();
info.put("name","YJL");
info.put("age",26);
root.put("info",info);
//6.进行合并,调用模板的 merge 方法, 将其进行填充。
StringWriter stringWriter=new StringWriter();
template.merge(root, stringWriter);
System.out.println("输出信息值:"
+stringWriter.toString());
}

Velocity的使用

二.二.二 If 条件语句 展示

二.二.二.一 If 条件语句 vm

创建 if.vm 文件

## 放置if
## 可以使用条件表达式,进行处理。
#if(>120)
年龄输入错误
#end
你的性别是:
#if(=='男')
男性
#else
女性
#end
你的成绩是:
#if(>90)

#elseif(>80)

#elseif(>70)

#elseif(>60)

#else

#end
二.二.二.二 If 条件语句 开发
@Test
public void ifFillTest()throws Exception{
//1. 创建模板引擎
VelocityEngine velocityEngine=new VelocityEngine();
//2. 设置属性
velocityEngine.setProperty(
RuntimeConstants.RESOURCE_LOADER,"classpath"
);
velocityEngine.setProperty(
"classpath.resource.loader.class",
ClasspathResourceLoader.class.getName()
);
//3. 进行初始化
velocityEngine.init();
//4.获取对应的模板信息
Template template=velocityEngine.getTemplate("if.vm");
//5. 构建 VelocityContext 对象,里面放置内容
Map<String,Object> root=new HashMap<>();
root.put("age",130);
root.put("sex","男");
root.put("score",86);
VelocityContext velocityContext=new VelocityContext(root);
//6. 找到StringWriter对象,进行合并
StringWriter stringWriter=new StringWriter();
template.merge(velocityContext,stringWriter);
System.out.println("输出信息:"+stringWriter.toString());

}

Velocity的使用

二.二.三 foreach 循环语句 展示

二.二.三.一 foreach 循环语句 vm

创建 foreach.vm 文件

#[[ 放置foreach 循环语句,进行处理 ]]#
## 放置 list或者数组 array
#foreach ($hobby in $hobbys)
$hobby
#end
#if()
<ul>
#foreach($user in $users)
<li></li>
#end
</ul>
#end
## 放置map语句
#foreach($key in $infoMap.keySet())
------>)}
#end
二.二.三.二 foreach 循环语句 开发

User.java

@Data
public class User {
private Integer id;
private String name;
private Integer sex;
private Integer age;
private String description;
}
@Test
public void foreachTest() throws Exception{
//1.创建 VelocityEngine 引擎
VelocityEngine velocityEngine=new VelocityEngine();
//2. 设置属性
velocityEngine.setProperty(
RuntimeConstants.RESOURCE_LOADER,"classpath"
);
velocityEngine.setProperty(
"classpath.resource.loader.class",
ClasspathResourceLoader.class.getName()
);
//3. 进行初始化
velocityEngine.init();
//4.获取模板
Template template=velocityEngine.getTemplate("foreach.vm");
//5.进行填充数据
Map<String,Object> root=new HashMap<>();
String[] hobbys=new String[4];
hobbys[0]="A";
hobbys[1]="B";
hobbys[2]="C";
hobbys[3]="D";
root.put("hobbys",hobbys);
List<User> userList=getUserList();
root.put("users",userList);

Map<String,Object> infoMap=new HashMap<>();
infoMap.put("name","YJL");
infoMap.put("age",26);
infoMap.put("sex","男");
root.put("infoMap",infoMap);

//6. 创建 VelocityContext 对象,填充数据。
VelocityContext velocityContext=new VelocityContext(root);
//7.
StringWriter stringWriter=new StringWriter();
//8. 通过 merge 方法,进行填充数据。
template.merge(velocityContext,stringWriter);
System.out.println("输出内容:"+stringWriter.toString());
}
private List<User> getUserList() {
List<User> userList=new ArrayList<>();
for(int i=1;i<=10;i++){
User user=new User();
user.setId(i);
user.setName("蝴蝶"+i);
user.setAge(i*3+1);
user.setSex(i%2);
user.setDescription("一个简单的描述");
userList.add(user);
}
return userList;
}

Velocity的使用

二.二.四 macro宏语句 展示

二.二.四.一 macro宏语句 vm

创建 macro.vm 文件

## 这是宏,可以理解成一个函数。
## 声明宏 sayHello 是方法名, $name 为参数
#macro(sayHello $name)
我们要讲述: $name
#end

## 使用宏
#sayHello("周小欢和岳泽霖的故事")

## 定义加法
#macro(add $num1,$num2)
#set($total=$num1+$num2)
## 直接使用相加的操作,还是字符串。
$num1+$num2=
#end
#add(2,3)
二.二.四.二 macro宏语句 开发
@Test
public void macroTests() throws Exception{
//1. 初始化模板引擎
VelocityEngine ve=new VelocityEngine();
//2. 设置相应的属性信息
ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader
.class.getName());
//3. 进行初始化
ve.init();
//4.获取模板文件
Template template=ve.getTemplate("macro.vm","utf-8");
//5.设置变量
VelocityContext velocityContext=new VelocityContext();
velocityContext.put("name","岳泽霖");
//6.进行合并,调用模板的 merge 方法, 将其进行填充。
StringWriter stringWriter=new StringWriter();
template.merge(velocityContext, stringWriter);
System.out.println("输出信息值:"
+stringWriter.toString());
}

Velocity的使用

二.二.五 include 包含文件

二.二.五.一 include 文件 vm

创建 foot.vm

<hr>
<i>
Copyright (c) 2000 <a href="https://www.ctyun.cn/portal/link.html?target=top.yueshushu.com">yueshushu_top</a>,
<br>
All Rights Reserved.
</i>

创建 footInclude.vm

<html>
<head>
<title>Include page</title>
</head>
<body>
<h1>Include page</h1>
<p>
## -- 放置进去, #include 填充进去。 #include 填充进去。
谢谢您来关注我:
#include ("foot.vm")
</body>
</html>
二.二.五.二 include 开发
@Test
public void includeFillTest()throws Exception{
//1. 创建模板引擎
VelocityEngine velocityEngine=new VelocityEngine();
//2. 设置属性
velocityEngine.setProperty(
RuntimeConstants.RESOURCE_LOADER,"classpath"
);
velocityEngine.setProperty(
"classpath.resource.loader.class",
ClasspathResourceLoader.class.getName()
);
//3. 进行初始化
velocityEngine.init();
//4.获取对应的模板信息
Template template=velocityEngine.getTemplate("footInclude.vm");
//5. 构建 VelocityContext 对象,里面放置内容
Map<String,Object> root=new HashMap<>();
root.put("name","两个蝴蝶飞");
VelocityContext velocityContext=new VelocityContext(root);
//6. 找到StringWriter对象,进行合并
StringWriter stringWriter=new StringWriter();
template.merge(velocityContext,stringWriter);
System.out.println("输出信息:"+stringWriter.toString());

}

Velocity的使用

三. 使用 Velocity 配置模板文件

可以使用 Velocity 的配置文件, 通过往模板里面填充属性,来创建特定的文件。

如生成一个基本的 Main 类

三.一 模板 vm

package ;
/**
@author: 两个蝴蝶飞
@Date:
@Description:
*/
public class {
/**
功能描述:
*/
public static void main(String []args){
System.out.println("");
}
}

三.二 模板类创建

public class MainTests {
@Test
public void mainTests() throws Exception{
//1. 初始化模板引擎
VelocityEngine ve=new VelocityEngine();
//2. 设置相应的属性信息
ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader
.class.getName());
//3. 进行初始化
ve.init();
//4.获取模板文件
Template template=ve.getTemplate("main.vm","utf-8");
//5.设置变量
Map<String,Object> root=getMainMap();
VelocityContext velocityContext=new VelocityContext(root);
//6.进行处理,发送到模板文件里面。
PrintWriter printWriter=new PrintWriter("src\\main\\java\\com\\zk\\velocity\\VelocityMain.java");
template.merge(velocityContext,printWriter);
//刷新并关闭
printWriter.flush();
printWriter.close();
System.out.println("生成文件成功");

}
private Map<String,Object> getMainMap() {
Map<String,Object> root=new HashMap<>();
root.put("packageName","com.zk.velocity");
root.put("author","zk");
root.put("createDate",new Date());
root.put("classDescription","一个测试Velocity 自动生成类");
root.put("className","VelocityMain");
root.put("mainMethodDesc","一个普通的测试方法");
root.put("info","Velocity 创建类生成信息");
return root;
}
}

Velocity的使用

生成的模板文件类:

Velocity的使用

本章节的代码放置在 github 上:

​​https://github.com/yuejianli/springboot/tree/develop/Velocity​​

谢谢您的观看,如果喜欢,请关注我,再次感谢 !!!

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

TEZNKK3IfmPf