企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一、Freemarker简介 FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写。FreeMarker我们的第一印象是用来替代JSP的,但是与JSP 不同的是FreeMarker 模板可以在 Servlet容器之外使用。可以使用它们来生成电子邮件、 配置文件、 XML 映射等。或者直接生成HTML。 虽然FreeMarker具有一些编程的能力,但通常由Java程序准备要显示的数据,由FreeMarker生成页面,通过模板显示准备的数据(如下图) ![](http://cdn.sojson.com/file/17-06-04-21-48-00/doc/5974404133) ## 二、整合 ~~~ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> ~~~ ~~~ spring: freemarker: cache: false # 缓存配置 开发阶段应该配置为false 因为经常会改 suffix: .html # 模版后缀名 默认为ftl charset: UTF-8 # 文件编码 template-loader-path: classpath:/templates/ ~~~ 如果没有,新建static和templates文件夹 ![](https://box.kancloud.cn/15a919bcbbf012a62166f8dfb198e941_441x688.png) ## 三、代码测试 ~~~ @Controller @RequestMapping("/template") public class TemplateController { @Resource(name="articleMybatisRestServiceImpl") ArticleRestService articleRestService; @GetMapping("/freemarker") public String index(Model model) { List<ArticleVO> articles = articleRestService.getAll(); model.addAttribute("articles", articles); //模版名称,实际的目录为:resources/templates/fremarkertemp.html return "fremarkertemp"; } } ~~~ ~~~ <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>freemarker简单示例</title> </head> <body> <h1>Hello Freemarker</h1> <table class=""> <tr> <td>作者</td> <td>教程名称</td> <td>内容</td> </tr> <#list articles as article> <tr> <td>${article.author}</td> <td>${article.title}</td> <td>${article.content}</td> </tr> </#list> </table> <img src="/image/template.png"> </body> </html> ~~~ 访问测试地址:[http://localhost:8888/template/freemarker](http://localhost:8888/template/freemarker) ![](https://box.kancloud.cn/44b42b22334bb1f4cf029f4caf2a48c0_789x842.png) ## 四、推荐 如果想进一步学习freemarker,请参考: [http://freemarker.foofun.cn/index.html](http://freemarker.foofun.cn/index.html)