session|session
Session 對象
可以使用 Session Object Storage Service特定使用者會話所需的資訊。這樣,當使用者在應用程式的 Web 頁之間跳轉時,儲存在 Session 對象中的變數將不會丟失,而是在整個使用者會話中一直存在下去。
當使用者請求來自應用程式的 Web 頁時,如果該使用者還沒有會話,則 Web 服務器將自動建立一個 Session 對象。當會話到期或被放棄後,伺服器將終止該會話。
Session 對象最常見的一個用法就是儲存使用者的喜好設定。例如,如果使用者指明不喜歡查看圖形,就可以將該資訊儲存在 Session 對象中。有關使用 Session 對象的詳細資料,請參閱“ASP 應用程式”部分的“管理會話”。
注意 工作階段狀態僅在支援 cookie 的瀏覽器中保留。
文法
Session.collection|property|method
集合
Contents 包含已用指令碼命令添加到會話中的項目。
StaticObjects 包含通過 <OBJECT> 標記建立的並給定了會話範圍的對象。
屬性
CodePage 將用於符號映射的字碼頁。
LCID 現場標識。
SessionID 返回使用者的會話驗證。
Timeout 應用程式工作階段狀態的逾時時限,以分鐘為單位。
方法
Abandon 該方法破壞 Session 對象並釋放其資源。
事件
global.asa 檔案中聲明下列事件的指令碼。
Session_OnEnd
Session_OnStart
有關以上事件及 global.asa 檔案的詳細資料, 請參閱 Global.asa 參考.
注釋
您可以在 Session 對象中儲存值。儲存在 Session 對象中的資訊在會話及會話範圍內有效。下列指令碼示範兩種類型的變數的儲存方式。
<%
Session("username") = "Janine"
Session("age") = 24
%>
但是,如果您將Object Storage Service在 Session對象中,而且您使用 VBScript 作為主指令碼語言。則必須使用關鍵字 Set。如下列指令碼所示。
<% Set Session("Obj1") = Server.CreateObject("MyComponent.class1") %>
然後,您就可以在後面的 Web 頁上調用 MyComponent.class1 揭示的方法和屬性,其調用方法如下:
<% Session("Obj1").MyMethod %>
也可以通過展開該對象的本機複本並使用下列指令碼來調用:
<%
Set MyLocalObj1 = Session("Obj1")
MyLocalObj1.MyObjMethod
%>
建立有會話範圍的對象的另一種方法是在 global.asa 檔案中使用 <OBJECT> 標記。
但是不能在 Session 對象中儲存內建對象。例如,下面每一行都將返回錯誤。
<%
Set Session("var1") = Session
Set Session("var2") = Request
Set Session("var3") = Response
Set Session("var4") = Server
Set Session("var5") = Application
%>
在將Object Storage Service到 Session 對象之前,必須瞭解它使用的是哪一種執行緒模式。只有那些標記為“Both”的對象才能儲存在沒有鎖定單線程會話的 Session 對象中。詳細資料, 請參閱“建立 ASP 組件”中的“選擇執行緒模式”。
若您將一個數組儲存在 Session對象中,請不要直接更改儲存在數組中的元素。例如,下列的指令碼無法運行。
<% Session("StoredArray")(3) = "new value" %>
這是因為 Session對象是作為集合被實現的。數組元素 StoredArray(3) 未獲得新的賦值。而此值將包含在 Application 對象集合中,並將覆蓋此位置以前儲存的任何資訊。
我們極力建議您在將數組儲存在 Session對象中時,在檢索或改變數組中的對象前擷取數組的一個副本。在對數組操作時,您應再將數組全部儲存在 Session 對象中,這樣您所做的任何改動將被儲存下來。下列的指令碼對此進行示範。
---file1.asp---
<%
'Creating and initializing the array
Dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"
'Storing the array in the Session object
Session("StoredArray") = MyArray
Response.Redirect("file2.asp")
%>
---file2.asp---
<%
'Retrieving the array from the Session Object
'and modifying its second element
LocalArray = Session("StoredArray")
LocalArray(1) = " there"
'printing out the string "hello there"
Response.Write(LocalArray(0)&LocalArray(1))
'Re-storing the array in the Session object
'This overwrites the values in StoredArray with the new values
Session("StoredArray") = LocalArray
%>
樣本
下列代碼將字串 MyName 分配給名為 name 的會話變數,並給名為 year 的會話變數指定一個值,而且為 some.Obj 組件的執行個體指定一個名為 myObj 的變數。
Session("name") = "MyName"
Session("year") = 96
Set Session("myObj") = Server.CreateObject("someObj")
%>