在spring boot中使用FreeMarker模板非常簡單方便,只需要簡單幾步就行:
1、引入依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>
2、建立模板:
<!DOCTYPE html><html><body><h4>親愛的${toUserName},你好。</h4><p style="color:blue;"> ${message}</p>祝:開心。</br>${fromUserName}</br>${time?date}</body></html>其中,${time?date}表示time是日期類型的變數,只取date部分。“?date”還可以使用“?datetime”或“?time”。
3、使用模板,測試案例:
@AutowiredConfiguration configuration; //freeMarker configuration@Testpublic void sendHtmlMailUsingFreeMarker() throws Exception {Map<String, Object> model = new HashMap<String, Object>();model.put("time", new Date());model.put("message", "這是測試的內容。。。");model.put("toUserName", "張三");model.put("fromUserName", "老許");Template t = configuration.getTemplate("welcome.ftl"); // freeMarker templateString content = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);logger.debug(content);//mailService.sendHtmlMail(to, "主題:html郵件", content);}
4、測試結果:
原始碼參考:https://github.com/xujijun/my-spring-boot
FreeMarker官網:http://freemarker.org/
附:使用迴圈遍曆一個List的模板:
<html><body><h3>發現錯誤。<a href="${errorLogLink}" target="_blank">點擊這裡查看詳情</a></h3> <h3>錯誤清單:</h3> <table border="1px solid #8968CD" style="border-collapse: collapse;"><tr><th>錯誤位置</th> <th>數量</th> <th>錯誤資訊</th> <th>錯誤類名</th> <th>更多資訊</th> </tr><#list errorList as error><tr><td>${error.pos}</td><td>${error.count}</td><td>${error.msg}</td><td>${error.eName!}</td><td>${error.details!}</td></tr></#list></table> </body></html>注意:最後那個兩個驚嘆號表示:如果error.eName/error.details的值為空白,則用空格代替。驚嘆號後面也可以加一個預設字串,在空值的時候代替空值。如果不加驚嘆號會報錯。