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. ‘a(chǎn)s 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網(wǎng)站的根目錄中,或者放到已配置為一個虛擬應用程序的目錄中,并且在該目錄中包含有其他示例文件。 讀取和存儲值 注意上面的例子怎樣讀取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網(wǎng)頁訪問時,需要進行相同的處理。用Application事件內(nèi)的代碼訪問Application對象中的值時,不要求這么做。這是因為在任何應用程序中只有一個Application對象的實例,并且其事件處理器的代碼只在沒有活動的用戶會話時進行。 也可以看到一個基本的用戶會話計數(shù)器是如何實現(xiàn)的。這里使用一個應用程序級的變量 Visit_count,當新的會話啟動時它就自動增加。 一般也不限制簡單地把值保存到Application 或Session對象中。例如,Web開發(fā)者的Web站點在http://webdev.wrox.co.uk上,有相應的一個global.asa文件,當一個新的會話啟動時該文件就在服務器上的數(shù)據(jù)庫中寫入相應的條目,數(shù)據(jù)細節(jié)從Request.ServerVariables集合中獲取。這提供了一個基本的方法統(tǒng)計訪問者的數(shù)量,并收集訪問者的一些基本信息。