spring boot 使用velocity模板(十六)

(不要使用这种模板了,spring boot最新版已经不支持了。使用FreeMarker吧:http://blog.csdn.net/clementad/article/details/51942629)

简单几步,在spring boot中使用velocity模板生成文本:

1、引入依赖

  1. <dependency>    
  2.     <groupId>org.springframework.boot</groupId>  
  3.     <artifactId>spring-boot-starter-velocity</artifactId>  
  4. </dependency>  


2、resources中创建templates目录


3、创建.vm模板文件welcome.vm:

  1. <html>  
  2. <body>  
  3. 亲爱的${toUserName},你好!  
  4.   
  5.     ${message}  
  6.   
  7. 祝:开心!  
  8. ${fromUserName}  
  9. ${time}  
  10.   
  11. </body>  
  12. </html>  


4、使用模板,测试用例:

  1. @Autowired  
  2. VelocityEngine velocityEngine;  
  3.   
  4. @Test  
  5. public void velocityTest(){  
  6.     Map<String, Object> model = new HashMap<String, Object>();  
  7.     model.put("time", XDateUtils.nowToString());  
  8.     model.put("message", "这是测试的内容。。。");  
  9.     model.put("toUserName", "张三");  
  10.     model.put("fromUserName", "老许");  
  11.     System.out.println(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "welcome.vm", "UTF-8", model));  
  12. }  


5、测试结果:

附:

velocity官网:http://velocity.apache.org/

velocity语法参考:http://velocity.apache.org/engine/devel/vtl-reference.html

源代码参考:https://github.com/xujijun/my-spring-boot

原文地址:https://www.cnblogs.com/MaxElephant/p/8142857.html