Springboot整合FreeMarker
Springboot整合FreeMarker
遇到的问题:我现在要将内容以表格的形式以String类型放在邮件中发送出去。
我刚开始的时候,表格这部分前端代表写死在Manager层,这样后期如果邮件样式变动的话,需要大改,会比较麻烦。
所以,我现在就需要在工程中整合FreeMarker,生成HTML页面并且以String的形式返回。
首先在pom加入maven依赖
<!-- freeMarker --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
然后,HTML的模板:
<table border="2px" align="center" bordercolor="blue"> <tr> <th>originId</th> <th>gmtCreated</th> <th>outOrderNo</th> </tr> <#list Orderlist as order> <tr> <td>${order.originId}</td> <td>${order.gmtCreated}</td> <td>${order.outOrderNo}</td> </tr> </#list> </table>
整合的代码:
public class Freemarker { public static void main(String[] args) { List<mailDo> list =new ArrayList<>(); mailDo order =new mailDo(); order.setGmtCreated("2018-05-03 10:00:00"); order.setOriginId("001"); order.setOutOrderNo("123451"); mailDo order1 =new mailDo(); order1.setGmtCreated("2018-05-02 10:20:30"); order1.setOriginId("002"); order1.setOutOrderNo("123452"); list.add(order); list.add(order1); HashMap root =new HashMap(); root.put("Orderlist", list); Configuration config = new Configuration(); config.setDefaultEncoding("UTF-8"); try { config.setDirectoryForTemplateLoading(new File("./src/main/resources/templates")); Template temp =config.getTemplate("mail.html"); StringWriter swriter = new StringWriter(); temp.process(root, swriter); System.out.println(swriter.toString()); } catch (IOException | TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
结果如下:
务实,说实话!