FreeMarker 是基於模板的文本生成工具:模板 + 數據模型 = 輸出文本。廣泛用於代碼生成、靜態頁生成、郵件模板、配置文件生成等場景。
org.freemarker:freemarker:2.3.32 (最新穩定版)import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
public class StringTemplateDemo {
public static void main(String[] args) throws Exception {
// 1. 創建配置 (2.3.32 版本需指定版本)
Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
// 2. 從字符串創建模板
String templateStr = "用戶名:${user};網址:${url};站點:${name}";
Template template = new Template("inline", new StringReader(templateStr), cfg);
// 3. 準備數據模型
Map model = new HashMap<>();
model.put("user", "lavasoft");
model.put("url", "https://www.example.com");
model.put("name", "示例站點");
// 4. 執行合並輸出
StringWriter out = new StringWriter();
template.process(model, out);
System.out.println(out.toString());
}
}
輸出:用戶名:lavasoft;網址:https://www.example.com;站點:示例站點
public class FileTemplateDemo {
private Configuration cfg;
public void init() throws IOException {
cfg = new Configuration(Configuration.VERSION_2_3_32);
// 設置模板加載目錄 (類路徑、文件系統均可)
cfg.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
}
public void process() throws Exception {
Map model = new HashMap<>();
model.put("user", "lavasoft");
model.put("url", "https://www.example.com");
model.put("name", "示例站點");
Template template = cfg.getTemplate("welcome.ftl");
template.process(model, new OutputStreamWriter(System.out, "UTF-8"));
}
public static void main(String[] args) throws Exception {
FileTemplateDemo demo = new FileTemplateDemo();
demo.init();
demo.process();
}
}
welcome.ftl<html>
<head><title>Welcome!</title></head>
<body>
<h1>Welcome ${user}!</h1>
<p>Latest product: <a href="${url}">${name}</a>!</p>
<hr>
尊敬的用戶您好:
用戶名:${user}; URL:${url}; 站點:${name}
</body>
</html>
| 語法 | 說明 | 示例 |
|---|---|---|
| ${var} | 變量插值 (自動轉義) | ${user} |
| <#if condition>...<#else>...#if> | 條件判斷 | <#if user??>歡迎<#else>訪客#if> |
| <#list items as item>...${item}...#list> | 遍歷集合 | <#list users as u>${u.name}#list> |
| <#include "header.ftl"> | 引入片段 | 公共頭部復用 |
| <#macro name(p)>...${p}...#macro> | 定義宏 (函數) | <@macro "參數" /> |
| ${var?html} | HTML 轉義 | 防 XSS |
| ${date?string("yyyy-MM-dd")} | 日期格式化 | 內建函數鏈 |
Configuration 線程安全,應用全局共享一個實例。RETHROW_HANDLER 讓異常拋出,由上層統一處理。?html 或配置 auto_escaping_policy 防 XSS。setDirectoryForTemplateLoading 路徑、模板文件名大小寫、後綴 .ftl。${var!} (默認值) 或 ${var??} (判空)。