萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JSP 動態生成靜態 HTML 頁面實作範例

核心原理

  1. 讀取模板檔案 (template.htm) 內容為字串
  2. 以佔位符 (#title#, #content#) 替換動態資料
  3. 寫入靜態 HTML 檔案至指定目錄
  4. 重導向至生成的靜態頁

html.jsp - 生成邏輯

<%@ 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);
%>

template.htm - 模板檔案

<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 有利

現代化替代方案

  • 模板引擎:Thymeleaf, FreeMarker, Velocity, Beetl — 支援邏輯判斷、迴佈、片段引入
  • 靜態站點生成器:Hugo, Jekyll, Next.js (SSG), Gatsby — 建構時生成
  • 反向代理快取:Nginx fastcgi_cache/proxy_cache、Varnish、CDN Edge 快取
  • 頁面碎片化:ESI (Edge Side Includes) 組合動態/靜態片段

適用場景判斷

✅ 適合:內容型網站 (新聞、部落格、產品頁)、更新頻率低、流量大、SEO 關鍵
❌ 不適合:高度個性化、即時互動、用戶狀態強相關、頻繁更新的頁面

copyright © 萬盛學電腦網 all rights reserved