[Java] 模板引擎 Velocity 随笔

Velocity 是一个基于 Java 的模板引擎。

本博文演示 Velocity 的 HelloWord 以及分支条件。

HelloWord.vm,模板文件。

templateDemo.java, 演示 Velocity 模板引擎。

App.java, 应用的入口

在 Eclipse 上,基于 maven 管理工具,运行后目录结构如下

源代码只存在于 ./src/main 目录下面。target 目录为 maven 生成输出的目录,可做参考。test 目录为测试代码目录,此处可忽略。

grs:test grs$ pwd
/Users/grs/Documents/Java/mavenDemo/test
grs:test grs$ tree
.
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── tony
│   │   │       └── test
│   │   │           ├── App.java
│   │   │           └── TemplateDemo.java
│   │   └── resources
│   │       └── HelloWord.vm
│   └── test
│       └── java
│           └── tony
│               └── test
│                   └── AppTest.java
└── target
    ├── classes
    │   ├── HelloWord.vm
    │   └── tony
    │       └── test
    │           ├── App.class
    │           └── TemplateDemo.class
    └── test-classes
        └── tony
            └── test
                └── AppTest.class

具体代码

HelloWord.vm,模板文件

Hello $name ! wwwwww
---
#if($value == 1)
value is 1, name is $name
#else
value is not 1, name is $name
#end

TemplateDemo,演示代码。需要注意的是,获取当前目录时,指向的是当前项目的根目录路径,所以在查找模板文件 HelloWord.vm 时,路径也是从项目根目录开始查找。

package tony.test;

import java.io.File;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class TemplateDemo {
    
    public static void main(){
        
        File file = new File(".");
        System.out.println(file.getAbsolutePath());
        
        try {
            VelocityEngine ve = new VelocityEngine();
            ve.init();
            
            Template template = ve.getTemplate("./src/main/resources/HelloWord.vm");
            
            VelocityContext context = new VelocityContext();
            context.put("name", "TTTTT");
            context.put("value", "1");
            
            StringWriter writer = new StringWriter();
            
            template.merge(context, writer);
            
            System.out.println(writer.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }        
    }
}

App 应用入口

package tony.test;

public class App 
{
    public static void main( String[] args )
    {        
        TemplateDemo.main();
    }
}

Eclipse 下的目录结构,以供参考

参考资料

Start up the Velocity Template Engine, javaWorld

Introduction to the Standard Directory Layout

原文地址:https://www.cnblogs.com/TonyYPZhang/p/5625458.html