快速依赖

  1. <dependency>
  2. <groupId>org.apache.velocity</groupId>
  3. <artifactId>velocity</artifactId>
  4. <version>1.7</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.velocity</groupId>
  8. <artifactId>velocity-tools</artifactId>
  9. <version>2.0</version>
  10. </dependency>

使用字符串模板

  1. // 初始化模板引擎
  2. VelocityEngine ve = new VelocityEngine();
  3. ve.init();
  4. String text = "Hello, ${name}";
  5. // 设置变量
  6. VelocityContext ctx = new VelocityContext();
  7. ctx.put("name", "Velocity");
  8. // 输出
  9. StringWriter sw = new StringWriter();
  10. ve.evaluate(ctx, sw, "test", text);
  11. System.out.println(sw.toString());

使用模板文件

  1. VelocityEngine ve = new VelocityEngine();
  2. ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
  3. ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
  4. ve.init();
  5. // 获取模板文件
  6. Template t = ve.getTemplate("template/hello.vm"); // resources下的template目录
  7. // 设置变量
  8. VelocityContext ctx = new VelocityContext();
  9. ctx.put("name", "Velocity");
  10. // 输出
  11. StringWriter sw = new StringWriter();
  12. t.merge(ctx, sw);
  13. System.out.println(sw.toString());

参考

https://www.jianshu.com/p/5913903324ff