Web 應用程式運行於伺服器端,接收 HTTP 請求並動態產生 HTML 回應。C++ Builder 將 CGI、ISAPI/NSAPI 等不同 Web 架構封裝為統一元件模型,開發者只需專注於業務邏輯,即可輕鬆建立跨平台的 Web 應用。本文透過兩個範例,完整示範從專案建立到部署測試的全流程。
TWebActionItem 集合,路由 HTTP 請求。Content 為輸出 HTML。PathInfo 分派請求至對應 Action Item。File → New → Web Server Application → 選 CGI Stand-alone executable(除錯方便,後續可轉 ISAPI)。
右鍵 WebModule → Action Editor → Add → 設定 PathInfo = /hello、Default = true。
void __fastcall TWebModule1::WebModule1WebActionItem1Action(
TObject *Sender, TWebRequest *Request, TWebResponse *Response, bool &Handled)
{
AnsiString html = "Hello!
Now is " +
TimeToStr(Time()) + "
";
Response->Content = html;
}
編譯產生 project1.exe,置於 Web 伺服器可執行目錄(需執行權限),瀏覽器訪問 https://server/cgi-bin/project1.exe/hello 即見問候與時間。
PathInfo = /formPageProducer1,HTMLDoc 設為表單 HTML(含 method="POST" action="/project1.exe/t3")。Response->Content = PageProducer1->Content();Thank You!
您好 <#T1>!
感謝您填寫問卷,您的 E-mail 為 <#T2>,我們將與您聯繫!
void __fastcall TWebModule1::PageProducer2HTMLTag(
TObject *Sender, TTag Tag, const AnsiString TagString,
TStrings *TagParams, AnsiString &ReplaceText)
{
ReplaceText = Request->QueryFields->Values[TagString] +
Request->ContentFields->Values[TagString];
}
PathInfo = /t3Response->Content = PageProducer2->Content();| 特性 | CGI | ISAPI/NSAPI |
|---|---|---|
| 進程模型 | 每請求一進程 | DLL 載入伺服器進程 |
| 效能 | 較低(進程建立開銷) | 高(記憶體常駐) |
| 除錯難度 | 容易(獨立 EXE) | 困難(DLL 鎖定) |
| 建議策略 | 開發/除錯階段 | 正式部署階段 |
inetinfo.exe 重啟才能覆蓋。掌握 WebModule 與 Action Item 的運作機制,即可用 C++ Builder 高效開發各類伺服器端 Web 應用。