Session 对象


可以使用 Session 对象存储特定用户会话所需的信息。这样,当用户在应用程序的 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
%>

但是,如果您将对象存储在 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
%>

在将对象存储到 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") 
 %>
本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3