springboot 使用FreeMarker模板(轉)


在spring boot中使用FreeMarker模板非常簡單方便,只需要簡單幾步就行:

1、引入依賴:

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

2、創建模板:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <body>  
  4. <h4>親愛的${toUserName},你好!</h4>  
  5.   
  6. <p style="color:blue;"> ${message}</p>  
  7.   
  8. 祝:開心!  
  9. </br>  
  10. ${fromUserName}  
  11. </br>  
  12. ${time?date}  
  13.   
  14. </body>  
  15. </html>  
其中,${time?date}表示time是日期類型的變量,只取date部分。“?date”還可以使用“?datetime”或“?time”。



3、使用模板,測試用例:

  1. @Autowired  
  2. Configuration configuration; //freeMarker configuration  
  3.   
  4. @Test  
  5. public void sendHtmlMailUsingFreeMarker() throws Exception {  
  6.     Map<String, Object> model = new HashMap<String, Object>();  
  7.     model.put("time"new Date());  
  8.     model.put("message""這是測試的內容。。。");  
  9.     model.put("toUserName""張三");  
  10.     model.put("fromUserName""老許");  
  11.       
  12.     Template t = configuration.getTemplate("welcome.ftl"); // freeMarker template  
  13.     String content = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);  
  14.   
  15.     logger.debug(content);  
  16.     //mailService.sendHtmlMail(to, "主題:html郵件", content);  
  17. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM