正 文

解析ASP的Application和Session对象


www.7dspace.com  更新日期:2005-11-22 4:17:47  七度空间


  使用Application和Session的事件

  ASP的Application和Session对象体现了其他ASP内置对象所没有的特征——事件。然而,正像在前面的对象成员表中看到的那样,这些都是ASP会话和应用程序的工作相联系的事件。

  1. Application和Session的事件处理器
 
  每当一个应用程序或会话启动或结束时,ASP触发一个事件。可以通过在一个特殊的文件中编写普通的脚本代码来检测和应答这些事件,这个文件名为global.asa,位于一个应用程序的根目录中(对于缺省的Web网站是\InetPub\WWWRoot目录,或是作为一个实际应用程序定义的一个文件夹)。这个文件可以包含一个或多个HTML的<OBJECT>元素,用于创建将在该应用程序或用户会话内使用的组件实例。

  下面的代码是global.asa文件的一个例子。我们只关注<OBJECT>元素以及以Set关键字开始的那些代码行:

<!-- Declare instance of the ASPCounter component
with application-level scope //-->
<OBJECT ID=”ASPCounter” RUNAT=”Server” SCOPE=”Application”
PROGID=”MSWC.Counters”>
</OBJECT>

<!-- Declare instance of the ASPContentLimk component
with session-level scope //-->
<OBJECT ID=”ASPContentLink” RUNAT=”Server” SCOPE=”Session”
PROGID=”MSWC.NextLink”>
</OBJECT>

<SCRIPT LANGUAGE=”VBScript” RUNAT=”Server”>

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网站的根目录中,或者放到已配置为一个虚拟应用程序的目录中,并且在该目录中包含有其他示例文件。

4页,页码:[1] [2] [3] [4] 

上一篇:图解:入侵国内某知名出版社网站全记录
下一篇:ASP.NET中实现Flash与.NET的紧密集成
作者:  来源:codeof ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐