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 %>

相关文章
相关标签/搜索