遍歷Cookies集合 為了使用Cookies集合更加方便,可使用名稱為Haskeys的附加屬性。假如訪問的cookie本身也是個集合,即它是一個多值的cookie,這將返回True。使用Haskeys屬性,可以遍歷完整的Request.Cookies集合,從而獲得所有cookie的列表及它們的值。 For Each objItem In Request.Cookies If Request.Cookies(objItem).HasKey Then ‘Use another For Each to iterate all subkeys For Each objItemKey in Request.Cookies(objItem) Response.Write objItem & “(“ & objItemKey & “) = “_ & Request.Cookies(objItem)(objItemKey) & “<BR>” Next Else ‘PRint out the cookie string as normal Response.Write objItem & “ = ”& Request.Cookies(objItem) & “<BR>” End If Next 這非常類似于前面的從Request.Form集合中提取多個值的復雜代碼。但是這里可以使用Haskeys屬性來判別每個條目是否為一個集合。而在Form例子里,必須查詢Request.Form(item_name).Count屬性,這是因為Form集合(和所有的除cookie外的其他集合)成員不可能是真正的集合。ASP只是做了“幕后”的工作,得到了每個多條目集合的值。
在本書的后面附錄中可以找到所有ServerVariables集合成員的一個列表,及其值的說明。然而,可從前面討論的在請求頁面時從客戶端發出的HTTP報頭中見到這些成員。當請求收到后,Web服務器也增加它本身的一些值到集合中,正如上面可以看到的運行在IIS 5.0創建的頁面那樣。 1) 頁面是如何工作的 為了創建這個頁面,使用了本章前面在對Form集合和如何訪問其值的討論中所看到的完全相同的代碼。例如,遍歷所有的集合(除Request.Cookies外),使用: For Each objItem In Request.collection_name Response.Write objItem & “ = “ & Request.collection_name(objItem) & “<BR>” Next 遍歷Cookies集合,可以使用: For Each objItem In Request.Cookies If Request.Cookies(objItem).HasKeys Then ‘Use another For ... Each to iterate all keys of dictionary For Each objItemKey in Request.Cookies(objItem) Resonse.Write objItem objItem & “(“ & objItemKey & “) = “_ & Request.Cookies(objItem)(objItemKey) & “<BR>” Next Else ‘Print out the cookie string as normal Response.Write objItem & “ = “ & Request.Cookies(objItem) & “<BR>” End If Next 為獲得TotalBytes屬性,可簡單地使用: Request.TotalBytes = <% = Request.TotalBytes %><P> 讀者應該注意到,在兩個集合中出現的某些值不是從窗體的HTML控件中直接得到的。QueryString集合包括了兩個名為chapter和sample的值,如下圖所示:
各種Response屬性說明了將要用來創建HTTP報頭的一些信息。HTTP報頭頁面的其他部分(HTML和文本內容)被發往到客戶端。這些屬性中的一些以及所有的Response對象的方法均有鏈接,允許讀者打開另一個頁面來顯示其使用情況。我們稍后再回到這些頁面。 頁面中的屬性是通過讀取相應的屬性并插入到頁面中創建的。由于這些是動態鏈接,通過<A>元素來選擇。 <A HREF = ”headers/expiretet_form.asp”>Response.CacheControl</A> = <% = Resposne.CacheControl %><BR> 鏈接到每個方法是通過<A>鏈接元素,頁面中唯一復雜的部分是Response.Cookies集合。通過只能訪問cookie,讀取Request.Cookies集合中的值。當訪問Response.Cookie集合時,必須在發送任何輸出到客戶端之前結束對它的所有引用。因此在頁面的上部,通過遍歷集合創建頁面的HTML放在一個局部字符串變量中。 StrCookies = “” ‘We can only read the key names and not the values because ‘the Response.Cookies collection is ‘write only’ For Each objItem In Response.Cookies If Response.Cookies(objItem).HasKeys Then ‘Use another For Each to iterate all subkeys For Each objItemKey in Response.Cookies(objItem) StrCookies = strCookies & objItem & “(“ &objItemKey & “)<BR>” Next Else ‘print out the cookie as normal strCookies = strCookies & objItem & “<BR>” End If Next 然后在頁面的適當點上插入結果。 <P><DIV CLASS=”subhead”>The Response.Cookies Collection</DIV> <I><A HREF=”cookies/setcookies.asp”>Response.Cookies</A> is a write-only collection so the values cannot be displayed</I><BR> <% = strCookies %>