使用 Velocity 生成靜態(tài)頁面

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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容