|
|
存储特定用户会话所需的信息,当用户在应用程序的 Web 页之间跳转时,存储在 Session 对象中的变量将不会丢失,而是在整个用户会话中一直存在下去
Session.collection|property|method
| Contents | 基本集合,使用标准内部对象 Dictionary 存放数据 |
| LastAccessTime | 查询回话最后访问时间,返回的时间为最后一次 asp 请求接受时间 |
| SessionID | SessionID 属性返回用户的会话标识 |
| SessionKey | 查询当前会话的标识字符串 |
| Timeout | Timeout 属性以分钟为单位为该应用程序的 Session 对象指定超时时限 |
| Abandon | Abandon 方法删除所有存储在 Session 对象中的对象并释放这些对象的源。如果您未明确地调用 Abandon 方法,一旦会话超时,服务器将删除这些对象 |
| Reset | 清除 Session 中的全部数据和对象,并与浏览器重新建立会话 |
当用户请求来自应用程序的 Web 页时,如果该用户还没有会话,则 Web 服务器将自动创建一个 Session 对象。当会话过期或被放弃后,服务器将终止该会话。
Session 对象最常见的一个用法就是存储用户的首选项。例如,如果用户指明不喜欢查看图形,就可以将该信息存储在 Session 对象中。
您可以在 Session 对象中存储值。存储在 Session 对象中的信息在会话及会话作用域内有效。下列脚本演示两种类型的变量的存储方式。
<%
Session("username") = "Janine"
Session("age") = 24
%>
但是,如果您将对象存储在 Session对象中,而且您使用 VBScript 作为主脚本语言。则必须使用关键字 Set。如下列脚本所示。
<% Set Session("Obj1") = Server.CreateObject("MyComponent.class1") %>
然后,您就可以在后面的 Web 页上调用 MyComponent.class1 揭示的方法和属性,其调用方法如下:
<% Session("Obj1").MyMethod %>
也可以通过展开该对象的本地副本并使用下列脚本来调用:
<%
Set MyLocalObj1 = Session("Obj1")
MyLocalObj1.MyObjMethod
%>
在将对象存储到 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")
%>