Spring Boot 中实现 FreeMarker 模板
在 Spring Boot 中集成 FreeMarker 模板引擎非常简单,FreeMarker 是一种基于模板生成文本输出的工具(如 HTML、XML、CSV 等)。以下是详细步骤和代码示例:
1. 添加依赖
在 pom.xml
中添加 FreeMarker 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2. 配置 FreeMarker
在 application.properties
或 application.yml
中配置模板路径和格式(可选):
# 设置模板文件后缀和编码
spring.freemarker.suffix=.ftl
spring.freemarker.charset=UTF-8
# 关闭模板缓存(开发时方便调试,生产环境建议开启)
spring.freemarker.cache=false
# 自定义模板路径(默认在 src/main/resources/templates/)
spring.freemarker.template-loader-path=classpath:/templates/
3. 创建模板文件
在 src/main/resources/templates/
下创建 FreeMarker 模板文件(如 welcome.ftl
):
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
<p>Current time: ${currentTime?string("yyyy-MM-dd HH:mm:ss")}</p>
<#if user.isAdmin>
<p>Welcome, Admin!</p>
<#else>
<p>Welcome, User!</p>
</#if>
<ul>
<#list items as item>
<li>${item}</li>
</#list>
</ul>
</body>
</html>
4. 编写控制器
创建一个 Spring MVC 控制器,渲染模板并传递数据:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Controller
public class WelcomeController {
@GetMapping("/welcome")
public String welcome(Model model) {
// 准备数据
Map<String, Object> data = new HashMap<>();
data.put("name", "Alice");
data.put("currentTime", LocalDateTime.now());
data.put("user", new User("Alice", true));
data.put("items", Arrays.asList("Item1", "Item2", "Item3"));
// 将数据添加到 Model(键为模板中的变量名)
model.addAllAttributes(data);
return "welcome"; // 对应 templates/welcome.ftl
}
// 示例用户类
private static class User {
private String name;
private boolean isAdmin;
public User(String name, boolean isAdmin) {
this.name = name;
this.isAdmin = isAdmin;
}
// Getters(FreeMarker 需要通过 getter 访问属性)
public String getName() { return name; }
public boolean isAdmin() { return isAdmin; }
}
}
5. 运行并测试
启动 Spring Boot 应用,访问 http://localhost:8080/welcome
,将看到渲染后的 HTML 页面。
6. FreeMarker 常用语法
- 变量输出:
${variable}
- 条件判断:
<#if condition>...</#if> <#else>...</#else>
- 循环遍历:
<#list items as item> ${item_index}: ${item} </#list>
- 日期格式化:
${date?string("yyyy-MM-dd")}
- 注释:
<#-- 注释内容 -->
7. 高级配置(可选)
如果需要自定义 FreeMarker 配置(如全局函数、共享变量),可创建 @Configuration
类:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
@Configuration
public class FreeMarkerConfig {
@Bean
public freemarker.template.Configuration freemarkerConfiguration() throws IOException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));
cfg.setDefaultEncoding("UTF-8");
// 添加共享变量
cfg.setSharedVariable("globalFunc", new GlobalFunctions());
return cfg;
}
}
总结
- 优势:FreeMarker 在 Spring Boot 中开箱即用,适合生成结构化文本(如 HTML 页面、邮件模板)。
- 扩展性:可通过自定义指令、函数扩展模板逻辑。
- 对比 Thymeleaf:FreeMarker 更轻量,但 Thymeleaf 支持原生 HTML 模板(无需编译),适合前后端分离场景。
通过以上步骤,你可以快速在 Spring Boot 中集成 FreeMarker 并实现动态模板渲染。
- 随机文章
- 热门文章
- 热评文章
- 了解抑郁症:自我评估与心理测试测试抑郁症心理测试题
- 探索自我:通过心理测试了解你的内心世界心理测试小问题怎么解决
- 探索高智商世界:门萨入会测试与智商的奥秘门萨俱乐部入门智商评估测试题
- 用插件开发为鸿蒙开发加速:DevEco Studio的秘密武器【华为根技术】
- Java 微服务:如何实现服务发现与负载均衡?
- 大模型时代:程序员的 “体力” 与 “脑力” 之变
- 测你的性格像《且听凤鸣》中的谁
- Struts2框架小知识
- 用AI直接生成架构图的初步探索