1、Velocity的Maven依赖
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
2、Demo源码
template.vm
<html>
<body>
${name}, hello world!
Hello world, $name!
</body>
</html>
Demo.java
public class Demo {
public static void main(String[] args) {
try {
// 设置模板路径
Properties properties = new Properties();
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "d:\\");
// 初始化Velocity引擎;
VelocityEngine engine = new VelocityEngine();
engine.init(properties);
// 构造上下文环境,压入需要用到的变量
VelocityContext context = new VelocityContext();
context.put("name", "Velocity");
// 加载模板
Template template = engine.getTemplate("template.vm");
// 根据上下文解析模板与数据
StringWriter writer = new StringWriter();
template.merge(context, writer);
// 输出
System.out.println(writer.toString());
} catch (ResourceNotFoundException e) {
e.printStackTrace();
} catch (ParseErrorException e) {
e.printStackTrace();
} catch (MethodInvocationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出:
3、总结
看别人简单试了一下,记录下来!