template.htm) 內容為字串#title#, #content#) 替換動態資料<%@ page contentType="text/html;charset=utf-8" import="java.io.*, cn.nbaia.newPage.newsPage.*, ..." %>
<%
// 1. 讀取模板
String templatePath = request.getRealPath("/") + "test/template.htm";
String templateContent;
try (FileInputStream fis = new FileInputStream(templatePath)) {
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
templateContent = new String(bytes, "UTF-8");
}
// 2. 獲取動態資料
int newsId = 2484; // request.getParameter("id")
News news = new NewsCtl().selectOneById(newsId);
String title = (news.getTitle() != null) ? news.getTitle() : "";
String content = (news.getContent() != null) ? news.getContent() : "";
// 3. 替換佔位符
templateContent = templateContent.replaceAll("#title#", title);
templateContent = templateContent.replaceAll("#content#", content);
// 4. 生成靜態檔案名 (可用 ID、時間戳、UUID)
String fileName = newsId + ".html";
String saveDir = request.getRealPath("/") + "filename/";
new File(saveDir).mkdirs();
String filePath = saveDir + fileName;
// 5. 寫入檔案 (指定 UTF-8 編碼)
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(templateContent.getBytes("UTF-8"));
}
// 6. 重導向至靜態頁
response.sendRedirect("../filename/" + fileName);
%>
<html>
<head>
<title>jsp</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<!-- 頁頭引入 -->
<span id="showTop"></span>
<script>
function topOnDownloadDone(d) { showTop.innerHTML = d; }
oDownload.startDownload('inc/top.jsp', topOnDownloadDone);
</script>
<table width="778" align="center">
<tr><td valign="top" bgcolor="#FFFFFF">
<div align="center" class="d9p">#title#</div>
</td></tr>
<tr><td valign="top" bgcolor="#FFFFFF">
<div align="center" class="d9p">#content#</div>
</td></tr>
</table>
<!-- 頁尾引入 -->
<span id="showBottom"></span>
<script>
function bottomOnDownloadDone(d) { showBottom.innerHTML = d; }
oDownload.startDownload('inc/bottom.jsp', bottomOnDownloadDone);
</script>
</body></html>
| 環節 | 注意事項 |
|---|---|
| 模板讀取 | 用 request.getRealPath("/") 取得絕對路徑,指定編碼讀取 |
| 佔位符替換 | replaceAll 使用正則,特殊字元需轉義;大量替換考慮 StringBuilder 或模板引擎 |
| 檔案寫入 | 目錄預先建立,getBytes("UTF-8") 確保編碼一致 |
| 併發安全 | 同一文件名併發寫入會覆蓋,建議加鎖或唯一命名 |
| 靜態化優勢 | 減輕資料庫/應用伺服器壓力、CDN 快取友善、SEO 有利 |
fastcgi_cache/proxy_cache、Varnish、CDN Edge 快取✅ 適合:內容型網站 (新聞、部落格、產品頁)、更新頻率低、流量大、SEO 關鍵
❌ 不適合:高度個性化、即時互動、用戶狀態強相關、頻繁更新的頁面