Internet 普及催生大量企業級 Web 應用需求。Web 應用程式核心任務:**接收 HTTP 請求 → 內部處理 (資料庫/邏輯) → 回傳 HTTP 回應**。Windows 平台主流兩種實作:**CGI (Common Gateway Interface)** 與 **ISAPI/NSAPI**。本文系統解析 HTTP/HTML 規範、CGI 與 ISAPI 架構差異,並以 C++Builder 6 示範 ISAPI 開發全流程。
請求訊息:
Method Request-URI HTTP-Version
Headers (General|Request|Entity)
(blank line)
Message-Body
回應訊息:
HTTP-Version Status-Code Reason-Phrase
Headers (General|Response|Entity)
(blank line)
Message-Body
GET:取得資源HEAD:僅取得標頭 (測試資源存在性/修改時間)POST:提交資料 (表單、上傳)PUT:上傳/更新資源| 類別 | 含義 | 典型範例 |
|---|---|---|
| 1xx | 資訊/繼續處理 | 100 Continue |
| 2xx | 成功 | 200 OK, 201 Created |
| 3xx | 重導向 | 301 Moved Permanently, 302 Found |
| 4xx | 客戶端錯誤 | 400 Bad Request, 404 Not Found |
| 5xx | 伺服器錯誤 | 500 Internal Server Error, 503 Service Unavailable |
<a href="/scripts/app.dll/path?query"> → GET 請求,查詢字串在 QueryString<form action="app.dll" method="POST"> → POST 請求,資料在 Message-Body,格式 name=value&name2=value2text, checkbox, radio, select, submit 等| 特性 | CGI | ISAPI/NSAPI |
|---|---|---|
| 執行模型 | 每請求建立**新進程** | DLL 載入**伺服器進程空間**,以**執行緒**服務 |
| 效能 | 進程建立/銷毀開銷大 | 極高,僅首次載入 DLL |
| 資源共享 | 困難 (進程隔離) | 容易 (記憶體共享、連線池) |
| 開發語言 | 任意 (EXE/Script) | C/C++/Delphi (DLL) |
| 穩定性風險 | 低 (進程隔離) | 高 (DLL 錯誤可能癱瘓伺服器) |
File → New → Web Server Application → ISAPI/NSAPI Dynamic Link Library
IDE 產生 TWebModule 核心元件,封裝請求/回應物件。
WebModule,屬性 Actions → Add 新增動作MethodType:mtGet, mtPost, mtAny 等PathInfo:對應 URL 路徑 (如 /MyPath 對應 /scripts/app.dll/MyPath?query)Name:動作識別名稱void __fastcall TWebModule1::WebModule1WebActionItem1Action(
TObject *Sender, TWebRequest *Request, TWebResponse *Response, bool &Handled)
{
// 1. 解析請求
AnsiString query = Request->Query; // 查詢字串
AnsiString name = Request->QueryFields->Values["name"]; // 解析後名值對
AnsiString content = Request->Content; // POST 原始內容
AnsiString val = Request->ContentFields->Values["field"]; // POST 解析
// 2. 業務邏輯處理...
// 3. 建構回應
Response->ContentType = "text/html";
Response->Content = "Hello " + name + "!";
// 或使用 PageProducer 產生複雜 HTML
Handled = true; // 標記已處理
}
| 物件 | 關鍵屬性 | 對應 HTTP 欄位 |
|---|---|---|
| TWebRequest | Query, QueryFields, Content, ContentFields, Accept, UserAgent, Referer, Authorization... | 請求標頭/主體 |
| TWebResponse | Content, ContentType, ContentLength, StatusCode, Location, WWWAuthenticate... | 回應標頭/主體 |
掌握 HTTP/HTML 協定細節與 ISAPI 架構原理,配合 C++Builder RAD 開發優勢,可快速建構高效能、可維護的企業級 Web 應用系統。