Spring Boot 中实现 FreeMarker 模板
【摘要】 在 Spring Boot 中集成 FreeMarker 模板引擎非常简单,FreeMarker 是一种基于模板生成文本输出的工具(如 HTML、XML、CSV 等)。以下是详细步骤和代码示例: 1. 添加依赖在 pom.xml 中添加 FreeMarker 依赖:<dependency> <groupId>org.springframework.boot</groupId> <...
在 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 并实现动态模板渲染。
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)