如何建立一個Cookie?
為了建立一個Cookie,您需要使用Response.Cookies命令。在下面的例子中,我們將建立一個名為“姓氏”,並指定值“someValue”,它的cookie:
<%
Response.Cookies("lastname") = "Peterson"
%>
該Response.Cookies命令必須出現在<HTML>標記,否則你需要放在網頁頂部以下行:
<% response.buffer = true %>
也可以分配一個Cookie屬性,比如設定一個日期時,在Cookie到期。下面的例子建立了一個cookie,將在30天屆滿的。如果你想在Cookie到期儘快離開你的訪客,您必須設定值為1的Expires屬性。
<%
Response.Cookies("lastname") = "Peterson"
Response.Cookies("lastname").Expires = Now + 30
%>
下一個重要屬性是域屬性。這個cookie只能讀取域它源於。這是預設設定為其所在建立域,但您可以根據需要改變它。在有一個例子:
<%
Response.Cookies("lastname").Domain = "http://www.webcheatsheet.com"
%>
另外兩個重要的屬性是路徑和安全效能。 Path屬性指定的域,可以使用的cookie確切的路徑。
如果安全屬性被設定,那麼cookie將只能設定瀏覽器是否使用安全通訊端或https教程:/ /串連,但並不意味著該Cookie是安全的。它只是一個像所有其他的Cookie的文字檔。
在有一個例子:
<%
Response.Cookies("lastname").Path = "/cookies/"
Response.Cookies("lastname").Secure = True
%>
如何檢索Cookie的值?
現在的Cookie設定,我們需要檢索資訊。為了擷取cookie的值,需要使用Request.Cookies命令。在下面的例子,我們檢索名為“姓氏”,並列印出其價值的cookie值。
<%
someValue = Request.Cookies("lastname")
response.write("The cookie value is " & someValue)
%>
輸出將是“Cookie”。
使用Cookie字典
除了儲存簡單值,在Cookies集合cookie可以代表一個cookie字典。字典是一個構造類似於在這數組中的每個元素是由它的名字識別組成的數組。
基本上,餅乾字典只是一個Cookie,它可以容納幾個值。這些值被稱為鍵。這為您提供了一個cookie儲存在您的所有必要的資訊選項。例如,假設你要收集使用者的姓名,存放在一個cookie他們。在下面的例子,我們將建立一個名為“使用者”,將包含這些資訊的Cookie
<%
Response.Cookies("user")("firstname") = "Andrew"
Response.Cookies("user")("lastname") = "Cooper"
%>
當你需要引用在與鍵的cookie的值,您必須使用索引值。在有一個例子:
<%
Response.Write(Request.Cookies("user") ("firstname"))
Response.Write(Request.Cookies("user") ("lastname"))
%>
現在讓我們假設我們要讀取的所有您的伺服器發送到使用者的電腦上的Cookie。為了檢查是否有一個cookie的鍵或不,您必須使用特定的cookie HasKeys財產。下面的樣本示範如何做到這一點。
<%
Response.Cookies("lastname") = "Peterson"
Response.Cookies("user")("firstname") = "Andrew"
Response.Cookies("user")("lastname") = "Cooper"
%>
<%
'The code below iterates through the Cookies collection.
'If a given cookie represents a cookie dictionary, then
'a second, internal for...each construct iterates through
'it retrieving the value of each cookieKey in the dictionary.
Dim cookie
Dim cookieKey
for each cookie in Request.Cookies
if Request.Cookies(cookie).HasKeys Then
'The cookie is a dictionary. Iterate through it.
%>
The cookie dictionary <%=cookie%> has the
following values:<br />
<%
for each cookieKey in Request.Cookies(cookie)
%>
cookieKey: <%= cookieKey %><br />
Value:
<%=Request.Cookies(cookie)(cookieKey)%><br />
<%
next
else
'The cookie represents a single value.
%>
The cookie <%=cookie%> has the following value:
<%=Request.Cookies(cookie)%> <br />
<%
end if
next
%>