Velocity 可以作為 SpringMVC 的 View 使用,也可以用來生成郵件,靜態(tài)頁面等。
Velocity 模版中可以直接調(diào)用對(duì)象的方法,這點(diǎn)比 Freemarker 好用,if else foreach 等語句也更舒服。
Gradle 依賴
compile 'org.apache.velocity:velocity:1.7'
compile 'org.apache.velocity:velocity-tools:2.0'
VelocityTest
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Properties;
public class VelocityTest {
@Test
public void generate() {
// [1] 配置 Velocity
String templateDirectory = "/Users/Biao/view/";
Properties properties = new Properties();
properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templateDirectory);
properties.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8");
properties.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8");
Velocity.init(properties);
// [2] 讀取模版文件
Template template = Velocity.getTemplate("hello.vm");
// [3] 準(zhǔn)備模版使用的數(shù)據(jù)
VelocityContext ctx = new VelocityContext();
ctx.put("name", "Hello");
ctx.put("static", "static path");
// [4] 使用模版和數(shù)據(jù)生成靜態(tài)內(nèi)容,可以用來實(shí)現(xiàn)頁面靜態(tài)化,放在 Redis 或則 Nginx 下
Writer writer = new StringWriter();
template.merge(ctx, writer);
System.out.println(writer);
}
}
輸出:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>REST</title>
</head>
<body>
Hello 你好!<br>
不存在的屬性: $var2<br>
全局變量: static path<br>
Context Path: $request.contextPath --
</body>
</html>
hello.vm
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>REST</title>
</head>
<body>
$name 你好!<br>
不存在的屬性: $!var1 $var2<br>
全局變量: $static<br>
Context Path: $request.contextPath --
</body>
</html>