Freemarker快速入门(面向零基础)
什么是Freemarker?
想象你有个万能填空模板——Freemarker就是这样的工具!它能帮你把固定模板和变化的数据自动组合成最终文档。比如电商网站的商品页面,模板是固定的排版框架,数据是不同商品的名称、价格、图片,Freemarker就是帮你自动组装的"小助手"。
小白必知的三大特点:
简单如写字:语法就像普通文本加几个
${}
符号2. 免费开源:不用花一分钱,企业也爱用跨平台:Java项目都能用,网页/PDF/邮件统统能生成
3分钟上手实战
跟着做就能看到你的第一个Freemarker页面!
第一步:准备模板文件
在文件目录src/main/resources/templates创建welcome.ftl
文件(Freemarker模板后缀),内容如下:
<!DOCTYPE html>
<html>
<head>
<title>欢迎页面</title>
</head>
<body>
<h1>你好呀,${username}!</h1>
<!-- 这里会动态显示用户名 -->
<p>今天是 ${date?date},您有 ${taskCount} 条待办事项</p>
</body>
</html>
第二步:引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- apache 对 java io 的封装工具库 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
第三步:Java代码调用
// 创建数据模型(像装数据的购物车)
Map<String, Object> data = new HashMap<>();
data.put("username", "小白同学"); // 设置用户名
data.put("taskCount", 3); // 设置任务数
data.put("date", new Date()); // 自动获取当前日期
// 配置Freemarker引擎
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDirectoryForTemplateLoading(new File("/templates"));
// 生成最终HTML
Template template = cfg.getTemplate("welcome.ftl");
try (Writer out = new FileWriter("output.html")) {
template.process(data, out); // 关键一步:合并数据与模板!
}
第三步:查看结果
打开生成的output.html
,你会看到:
<h1>你好呀,小白同学!</h1>
<p>今天是 2023-10-15,您有 3 条待办事项</p>
常用语法卡片
💡 小白提示:遇到问题先查
${}
是否拼写正确——这是最常见的错误哦!
下一步学习建议
在Freemarker官网下载练习包
尝试修改模板里的${}变量
给商品列表添加循环展示功能
用<#if>实现"库存不足"的红色提示
评论区