Cookie 變量雖然存放在Client 端機器上,卻也不是永遠不會消失的。系統預設給Cookie 變量的有效時間是1000 分鐘,不過我們可以在程序中自行設定有效日期,只要指定Cookie 變量的Expires 屬性即可。使用語法如下所示:
Response.Cookies(CookieName).Expires=#日期#
若我們沒有指定Expires 屬性,則Cookie 變量將不會被儲存,會像Session 一樣瀏覽器關閉 結束瀏覽便被毀滅。不Cookie 一但設定有效期限后,除非我們將Expires 屬性設為「dbNull」, 否則有日期期限的Cookie 無法被移除。所謂「dbNull」值代表「空」值,「空」的意思是什么 都沒有;所以有設定有效日期的Cookie 就可以被移除。下列范例在使用者登入后,在一個月內 瀏覽頁都不需要再登入;并且每次登入時,程序自動將Cookie 有效期限往登入日期后延長一個 月:
<Html>
<ASP:Panel Id="Pan1" Runat="Server">
<Form Runat="Server">
<Table>
<Tr>
<Td>賬號:</Td>
<Td><Asp:TextBox Id="txtID" Runat="Server" /></Td>
</Tr>
<Tr>
<Td>密碼:</Td>
<Td><Asp:TextBox TextMode="Password" Id="txtPassword"
Runat="Server" /></Td>
</Tr>
</Table>
<ASP:Button Id="btnSubmit" Text="確定" OnClick="btnSubmit_Click"
Runat="Server"/>
<ASP:Button Id="btnReset" Text="清除" OnClick="btnReset_Click"
Runat="Server"/>
<ASP:Label Id="Label1" Text="請輸入賬號及密碼" Runat="Server"/>
</Form>
</ASP:Panel>
<ASP:Panel Id="Pan2" Runat="Server">
Hi! <ASP:Label Id="lblMsg" Runat="Server"/> ,歡迎光臨
</ASP:Panel>
<Script Language="VB" Runat="Server">
Sub Page_Load(Sender As Object,e As EventArgs)
If Request.Cookies.Item("MyWeb_UserID")=dbNull Or _
Request.Cookies.Item("MyWeb_UserID").Value="" Then
Pan2.Visible=False
Else
Response.Cookies.Item("MyWeb_UserID").Expires=Now.AddMonths(1)
lblMsg.Text=Request.Cookies.Item("MyWeb_UserID").Value
Pan1.Visible=False
End If
End Sub
Sub btnSubmit_Click(Sender As Object, e As EventArgs)
If txtID.Text="charles" and txtPassword.Text="1234" Then
Response.Cookies("MyWeb_UserID").Value=txtID.Text
Response.Cookies.Item("MyWeb_UserID").Expires=Now.AddMonths(1)
Pan1.Visible="False"
Pan2.Visible="True"
lblMsg.Text=txtID.Text
End If
End Sub
Sub btnReset_Click(Sender As Object, e As EventArgs)
txtID.Text=""
txtPassword.Text=""
End Sub
</Script>
</Html>
上述程序代碼范例中我們使用兩個Panel,分別為Pan1 以及Pan2;Pan1 為要求使用者輸入賬號及密碼,而Pan2 則為歡迎語。程序執行時若使用者的Cookie 不存在或沒有數據,將歡迎語隱藏;如下列程序代碼片段所示:
Sub Page_Load(Sender As Object,e As EventArgs)
If Request.Cookies.Item("MyWeb_UserID")=dbNull Or _
Request.Cookies.Item("MyWeb_UserID").Value="" Then
Pan2.Visible=False
Else
Response.Cookies.Item("MyWeb_UserID").Expires=Now.AddMonths(1)
lblMsg.Text=Request.Cookies.Item("MyWeb_UserID").Value
Pan1.Visible=False
End If
End Sub
上列程序代碼片段中我們先判斷Cookie 對象是否存在,以及確定Cookie 中是有內容;如果Cookie 不存在或是Cookie 內沒有資料,則顯示Pan1 要求使用者登入的畫面;倘若Cookie 存在,則顯示Pan2 出現歡迎語:
使用者若輸入正確的使用者名稱后,我們便將使用者賬號寫入Cookie 中,并指定有效期限為一個月內;如下程序代碼片段所示:
Sub btnSubmit_Click(Sender As Object, e As EventArgs)
If txtID.Text="charles" and txtPassword.Text="1234" Then
Response.Cookies("MyWeb_UserID").Value=txtID.Text
Response.Cookies.Item("MyWeb_UserID").Expires=Now.AddMonths(1)
Pan1.Visible="False"
Pan2.Visible="True"
lblMsg.Text=txtID.Text
End If
End Sub