
3.2 整合FreeMarker
FreeMarker是一个非常古老的模板引擎,可以用在Web环境或者非Web环境中。与Thymeleaf不同,FreeMarker需要经过解析才能够在浏览器中展示出来。FreeMarker不仅可以用来配置HTML页面模板,也可以作为电子邮件模板、配置文件模板以及源码模板等。Spring Boot中对FreeMarker整合也提供了很好的支持,主要整合步骤如下:
1. 创建项目,添加依赖
首先创建Spring Boot项目,然后添加spring-boot-starter-web和spring-boot-starter-freemarker依赖,代码如下:

2. 配置FreeMarker
Spring Boot对FreeMarker也提供了自动化配置类FreeMarkerAutoConfiguration,相关的配置属性在FreeMarkerProperties中,FreeMarkerProperties部分源码如下:

从该默认配置中可以看到,FreeMarker默认模板位置和Thymeleaf一样,都在classpath:/templates/中,默认文件后缀是.ftl。开发者可以在application.properties中对这些默认配置进行修改,部分常见配置如下:

3. 配置控制器
控制器和Thymeleaf中的控制器一样,这里不再重复。
4. 创建视图
按照配置文件,在resources/templates目录下创建books.ftl文件,内容如下:

代码解释:
• 第14行首先判断model中的books不为空并且books中有数据,然后进行遍历。
• 第15~21行表示遍历books集合,将集合中的数据通过表格展示出来。
5. 运行
在浏览器中输入“http://localhost:8080/books”,即可看到运行结果,如图3-2所示。

图3-2
本节重点介绍Spring Boot整合FreeMarker,并非FreeMarker的基础用法,关于FreeMarker的更多资料,可以查看https://freemarker.apache.org/。