在 Spring Boot 中使用 FreeMarker 模板引擎可以帮助你创建动态的 Web 页面。以下是详细的步骤和示例代码,介绍如何在 Spring Boot 项目里集成和使用 FreeMarker。
1. 添加依赖
如果你使用的是 Maven 项目,需要在 pom.xml 文件中添加 FreeMarker 相关依赖。Spring Boot 提供了对应的 Starter 依赖,可简化配置过程。在 标签内添加如下内容:
xml
org.springframework.boot
spring-boot-starter-freemarker
如果你使用 Gradle 项目,在 build.gradle 文件的 dependencies 块中添加:
groovy
implementation ‘org.springframework.boot:spring-boot-starter-freemarker’
2. 配置 FreeMarker
Spring Boot 对 FreeMarker 有默认的配置,但你也可以根据需求进行自定义配置。默认情况下,FreeMarker 模板文件存放在 src/main/resources/templates 目录下,后缀为 .ftl。
你可以在 application.properties 或 application.yml 中进行额外的配置,例如修改模板文件的后缀:
application.properties 配置示例
properties
spring.freemarker.suffix=.html
application.yml 配置示例
yaml
spring:
freemarker:
suff