asp cookies用法與cookies實例教程

如何建立一個Cookie?web

爲了建立一個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

若是安全屬性被設置,那麼cookie將只能設置瀏覽器是否使用安全套接字或https教程:/ /鏈接,但並不意味着該Cookie是安全的。它只是一個像全部其餘的Cookie的文本文件。oop

在有一個例子:
<%
Response.Cookies("lastname").Path = "/cookies/"性能

Response.Cookies("lastname").Secure = True
%>
如何檢索Cookie的值?code

如今的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) %>       &nbsp; &nbsp; cookieKey: <%= cookieKey %><br />       &nbsp; &nbsp; 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 %>

相關文章
相關標籤/搜索