Sub Application_onStart() ‘Create an instance of an ADO Recordset with application-level scope Set Application(“ADOConnection”) _ = Server.CreateObject(“ADODB.Connection”) Dim varArray(3) ; ‘Create a Variant array and fill it VarArray(0) = “This is a” VarArray(1) = “Variant array” VarArray(2) = “stored in the” VarArray(3) = “Application object” Application(“Variant_Array”) = varArray‘Store it in the Application Application(“Start_Time”) = CStr(Now) ‘Store the date/time as a string Application(“Visit_Count”) = 0 ‘Set Counter variable to zero End Sub
Sub Application_onEnd() Set Application(“ADOConnection”) = Nothing End Sub
Sub Sesson_onStart() ‘Create an instance of the AdRotator component with session-level scope Set Session(“ASPAdRotator”) = Server.CreateObject (“MSWC.AdRotator”) Dim varArray(3) ; ‘Create a Variant arry and fill it VarArray(0) = “This is a” VarArray(1) = “Variant array” VarArray(2) = “stored in the” VarArray(3) = “Session object” Session(“Variant_Array”) = varArray ‘Store it in the Session Session(“Start_Time”) = CStr(Now) ‘Store the date/time as a string
‘We can access the contents of the Request and Response in a Session_onStart ‘event handler for the page that initiated the session. This is the *only* ‘place that the ASP page context is available like this. ‘as an example, we can get the IP address of the user: Session(“Your_IP_Address”) = Request.ServerVariables (“REMOTE_ADDR”) Application.Lock intVisits = Application(“Visit_Count”) +1 Application(“Visit_Count”) = intVisits Application.Unlock End Sub
Sub Session_onEnd() Set Session(“ASPAdRotator”) = Nothing End Sub </SCRIPT> 因为这个global.asa文件用于本章中的示例页面,所以将需要将该文件放到Web网站的根目录中,或者放到已配置为一个虚拟应用程序的目录中,并且在该目录中包含有其他示例文件。 读取和存储值 注意上面的例子怎样读取Application和Session的变量,与在Request和Response对象的集合中所采取的方式相同。设置这些变量的值: Application(“variable_name”) = variable_value Application(“variable_name”) = variant_array_variable_name Set Application(“variable_name”) = object_reference 获取这些变量的值: variable_value = Application(“variable_name”) variant_array_variable = Application(“variable_name”) Set object_reference = Application(“variable_name”) 当然,对于Session对象可采取同样的方法。 可以看到,当从一个Session事件处理器访问时,怎样“锁定”(Lock)和“解锁”(unlock)该Application对象;当从一个ASP网页访问时,需要进行相同的处理。用Application事件内的代码访问Application对象中的值时,不要求这么做。这是因为在任何应用程序中只有一个Application对象的实例,并且其事件处理器的代码只在没有活动的用户会话时进行。 也可以看到一个基本的用户会话计数器是如何实现的。这里使用一个应用程序级的变量 Visit_count,当新的会话启动时它就自动增加。 一般也不限制简单地把值保存到Application 或Session对象中。例如,Web开发者的Web站点在http://webdev.wrox.co.uk上,有相应的一个global.asa文件,当一个新的会话启动时该文件就在服务器上的数据库中写入相应的条目,数据细节从Request.ServerVariables集合中获取。这提供了一个基本的方法统计访问者的数量,并收集访问者的一些基本信息。