萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Java

ASP 生成靜態 HTML 頁面最簡單法:FSO 讀取輸出內容直接寫檔

動態轉靜態最直觀的做法:利用 #include 將目標 .asp 的執行結果捕獲到 ``

  • 瀏覽器載入頁面時,IIS 先執行 ``,產生完整 HTML 並填入 textarea
  • 3. 使用者按下「生成」,表單 POST 回同頁 4. 伺服端取得 `Request.Form("asp2html")` (即靜態 HTML 內容),用 FSO 寫入 index.html

    完整程式碼 (makeasp2html.asp)

    <%@ Language=VBScript CodePage=65001 %>
    <% Option Explicit %>
    <html><head><title>ASP 轉靜態 HTML 產生器</title></head><body>
    <h2>生成靜態首頁 index.html</h2>
    
    <form method="post" action="">
      <textarea name="asp2html" style="display:none"><!--#include file="index.asp"--></textarea>
      <input type="submit" value="生成 HTML 頁面" />
    </form>
    
    <%
    If Request.Form("asp2html") <> "" Then
        Dim fso, fout, filename, content
        filename = "index.html"
        content  = Request.Form("asp2html")
        
        Set fso = Server.CreateObject("Scripting.FileSystemObject")
        Set fout = fso.CreateTextFile(Server.MapPath(filename), True, True)  ' True=覆寫, True=Unicode
        fout.Write content
        fout.Close
        Set fout = Nothing
        Set fso = Nothing
        
        Response.Write "

    ✅ 成功生成 " & filename & "!點此檢視

    " End If %> </body></html>

    優缺點分析

    優點缺點
    極簡:無模板語法、無替換邏輯需手動點擊生成,無法自動觸發
    所見即所得:含 CSS/JS/圖片完整輸出動態資料 (如 Session、QueryString) 會被「凍結」在生成當下
    相容性高:任何 ASP 頁面皆可用大頁面 textarea 可能超過表單大小限制 (需調整 `AspMaxRequestEntityAllowed`)

    進階改良建議

    1. 自動化:改用 `Server.Execute("index.asp")` 搭配 `Response.Buffer = True` 捕獲輸出,無需表單中介:
      Response.Buffer = True
      Server.Execute "index.asp"
      content = Response.Output
      Response.Clear
      ' 再寫檔...
      
    2. 批次生成:迴圈遍歷文章 ID,依樣畫葫蘆產生 article_123.html
    3. 檔名安全:過濾非法字元,避免路徑遍歷
    4. 編碼一致:確保產生的 .html 為 UTF-8,`` 與實際編碼一致

    適用場景

    • 首頁、頻道頁、專題頁等「全站同版、更新頻率低」的頁面
    • 虛擬主機不支援 ISAPI Rewrite / URL Rewrite 時的偽靜態替代方案
    • 快速原型、靜態化演示

    小結

    「Include 捕獲 + FSO 寫檔」是 ASP 生成靜態頁最低門檻的方法。理解其本質是**伺服端渲染結果的序列化存檔**,即可靈活應用於各種靜態化需求。若追求全自動、高效能,建議升級至 ASP.NET / PHP / Node.js 等現代框架配合靜態站點生成器 (SSG)。

    copyright © 萬盛學電腦網 all rights reserved