使用 Velocity 生成静态页面

Velocity 可以作为 SpringMVC 的 View 使用,也可以用来生成邮件,静态页面等。

Velocity 模版中可以直接调用对象的方法,这点比 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] 准备模版使用的数据
        VelocityContext ctx = new VelocityContext();
        ctx.put("name", "Hello");
        ctx.put("static", "static path");
        // [4] 使用模版和数据生成静态内容,可以用来实现页面静态化,放在 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>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容