靜態化是提升 Web 頁面性能、降低服務器壓力的經典手段。本文介紹兩種主流實現:基於字符串替換的簡易模板引擎,以及成熟的 FreeMarker 模板框架,附完整代碼示例。
核心思路:讀取 HTML 模板文件 → 以佔位符(如 ###title###)標記動態區域 → 字符串替換 → 輸出靜態文件。
<html>
<head>
<title>${title}</title>
</head>
<body>
${content}
</body>
</html>
import java.io.*;
import java.util.Calendar;
public class BuildHtml {
public static void main(String[] args) {
try {
// 動態數據
String title = "測試標題";
String content = "這是靜態頁面內容";
String editor = "admin";
// 1. 讀取模板
String templatePath = "template.html";
FileInputStream fis = new FileInputStream(templatePath);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
String template = new String(bytes, "UTF-8");
// 2. 替換佔位符
template = template.replace("###title###", title);
template = template.replace("###content###", content);
template = template.replace("###author###", editor);
// 3. 生成文件名(時間戳)
String fileName = Calendar.getInstance().getTimeInMillis() + ".html";
String outputPath = "/" + fileName; // 實際項目中應配置輸出目錄
// 4. 寫入文件
FileOutputStream fos = new FileOutputStream(outputPath);
fos.write(template.getBytes("UTF-8"));
fos.close();
System.out.println("靜態頁面生成成功:" + outputPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
優點:零依賴、邏輯簡單、易於理解。
缺點:無邏輯控制(循環、判斷)、佔位符衝突風險、擴展性差、編碼易出錯。
FreeMarker 是成熟的 Java 模板引擎,支持指令、表達式、內建函數、宏、嵌套模板等豐富功能,廣泛用於郵件生成、代碼生成、靜態頁生成等場景。
Template template = cfg.getTemplate("test.ftl");(cfg 為 Configuration 實例,模板緩存自動管理)Map<String, Object> 或 JavaBean 作為 roottemplate.process(root, writer); 將解析結果寫入 Writer(文件、字符串、HTTP 響應等)import freemarker.template.*;
import java.io.*;
import java.util.*;
public class FreeMarkerStaticGenerator {
public static void main(String[] args) throws Exception {
// 1. 配置 Configuration
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDirectoryForTemplateLoading(new File("templates"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// 2. 獲取模板
Template template = cfg.getTemplate("article.ftl");
// 3. 準備數據模型
Map<String, Object> root = new HashMap<>();
root.put("title", "FreeMarker 靜態化示例");
root.put("content", "支持邏輯判斷、循環、格式化等豐富功能。");
root.put("tags", Arrays.asList("Java", "FreeMarker", "靜態化"));
root.put("publishDate", new Date());
// 4. 輸出到文件
File outputFile = new File("output/article_" + System.currentTimeMillis() + ".html");
outputFile.getParentFile().mkdirs();
try (Writer out = new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")) {
template.process(root, out);
}
System.out.println("生成完成:" + outputFile.getAbsolutePath());
}
}
<html>
<head><title>${title}</title></head>
<body>
<h1>${title}</h1>
<p>${content}</p>
<ul>
<#list tags as tag>
<li>${tag}</li>
</#list>
</ul>
<p>發布時間:${publishDate?string("yyyy-MM-dd HH:mm")}</p>
</body>
</html>
| 維度 | 字符串替換 | FreeMarker |
|---|---|---|
| 依賴 | 無 | freemarker.jar |
| 邏輯支持 | 無 | 完整(判斷、循環、函數、宏) |
| 性能 | 極快(簡單替換) | 高(模板緩存、預編譯) |
| 維護性 | 差(佔位符硬編碼) | 優(模板與業務分離) |
| 適用場景 | 極簡頁面、臨時腳本、學習演示 | 生產環境、複雜頁面、代碼生成、郵件模板 |
生產環境強烈建議使用 FreeMarker 或 Thymeleaf、Velocity 等成熟引擎。若項目已引入 Spring Boot,可直接使用 spring-boot-starter-freemarker 實現零配置整合。