在 C++Builder WebSnap 或 IntraWeb 架構下,Cookie 的讀寫透過 TWebResponse 與 TWebRequest 介面完成。本文提供標準範例碼與關鍵參數說明。
void SetCookieExample() {
TStringList* cookies = new TStringList();
try {
cookies->Add("Answer=42"); // Cookie 內容:名稱=值
// SetCookieField 參數說明:
// 1. Values: TStringList* - Cookie 清單
// 2. Domain: AnsiString - 適用網域 (如 ".example.com"),NULL 為當前網域
// 3. Path: AnsiString - 適用路徑 (如 "/app"),NULL 為當前路徑
// 4. Expires: TDateTime - 到期時間,Now()+1 表示隔天同一時間
// 5. Secure: bool - true 僅 HTTPS 傳輸
Response->SetCookieField(cookies, NULL, NULL, Now() + 1, false);
} __finally {
delete cookies;
}
}
int GetCookieAnswer() {
// CookieFields 為 TStrings*,支援 Values["Name"] 索引
AnsiString val = Request->CookieFields->Values["Answer"];
if (val.IsEmpty()) return -1; // 未找到或已過期
try {
return StrToInt(val); // 可能拋出 EConvertError
} catch (const Exception&) {
return -1; // 格式錯誤視為無效
}
}
// OnAction 事件處理器
void __fastcall TWebModule1::WebActionItem1Action(TObject *Sender,
TWebRequest *Request, TWebResponse *Response, bool &Handled) {
// 1. 讀取既有 Cookie
AnsiString lastInput = Request->CookieFields->Values["LastInput"];
// 2. 取得表單新輸入
AnsiString newInput = Request->ContentFields->Values["UserInput"];
// 3. 回應頁面
Response->Content = "<html><body>"
"上次輸入: " + (lastInput.IsEmpty() ? "(無)" : lastInput) + "<br>"
"本次輸入: " + newInput + "<br>"
"</body></html>";
// 4. 寫入/更新 Cookie(有效期 30 天)
if (!newInput.IsEmpty()) {
TStringList* cookies = new TStringList();
try {
cookies->Add("LastInput=" + newInput);
Response->SetCookieField(cookies, NULL, "/", Now() + 30, false);
} __finally {
delete cookies;
}
}
Handled = true;
}
| 參數 | 型別 | 預設值 | 說明 |
|---|---|---|---|
| Domain | AnsiString | NULL (當前主機) | 設為 .example.com 可跨子網域共享;NULL 僅限當前主機 |
| Path | AnsiString | NULL (當前路徑) | 設為 / 全站有效;/app 僅限應用路徑 |
| Expires | TDateTime | Session Cookie (瀏覽器關閉失效) | Now()+365 一年有效;0 立即刪除 |
| Secure | bool | false | true 僅 HTTPS 傳輸,生產環境建議啟用 |
HTTPEncode),讀取時 HTTPDecode。Domain=.yourdomain.com(前綴點號)。false,部署腳本自動切換。SameSite,需手動在 Set-Cookie 標頭附加(Response->SetCustomHeader("Set-Cookie", "key=val; SameSite=Lax"))。HttpOnly(需手動加標頭)防止 XSS 竊取。Secure=true + SameSite=Strict/Lax。