In-depth study of application and session objects (including Global.asa)

Source: Internet
Author: User
Tags character set count iis numeric value readable sessions root directory
application|session| objects


When using ASP to write virtual community, online shopping and other programs, application and Session object play an important role, the flexibility and reasonable use of these two objects is the key to improve the quality of the program. The following let the author according to their own experience in this area, to you in-depth introduction of the ASP's two built-in objects.

Overview of members of a Application object

Application object members include collections, methods, and events for application objects.

Collection of ⒈application objects

Contents collection: A collection of all variables stored in Applicaiton objects that are not defined using the <OBJECT> element

StaticObjects: A collection of all the variables stored in the Application object, defined using the <OBJECT> element

Example: The following assignment is available in the Default.asp

Application ("a") = "a"

Application ("B") =128

Application ("C") =false

Then there are contents sets

Application.Contents (1) = "A" can also be written as application.contents ("a") = "a"

Application.Contents (2) =128 ' can also be written as application.contents ("B") =128

Application.Contents (3) =false ' can also be written as application.contents ("C") =false

In this article I recommend that you use classes such as Application.Contents ("a") in the call, because this is more intuitive, if the number of words to consider the order of assignment.

Methods of ⒉application objects

Contents.Remove ("Variable name"): Removes the specified variable from the Application.Contents collection

Contents.RemoveAll (): Remove all variables from the Application.Contents collection

Lock (): Locks the Application object so that only the current ASP page can access the content

Unlock (): Unlocking the Application object

Example: In the Default.asp:

Application ("a") = "a"

Application ("B") =128

Application ("C") =false

Response.Write application.contents (1) & "<br>"

Response.Write Application.Contents (2) & "<br>"

Response.Write Application.Contents (3) & "<br>"

Response.Write "after Remove B:"

Application.Contents.Remove ("B")

Response.Write application.contents (1) & "<br>"

Response.Write Application.Contents (2) & "<br>"

Execution results:

A

128

False

After Remove B:

A

False

If you want to delete all the variables in the collection with Application.contents.removeall, the lock and unlock methods are often used in practice, and the reader is more familiar with it.

⒊application Object Events

OnStart: The first time a user accessing a server occurs when a page is first accessed

OnEnd: When the last user's session has ended and the session's OnEnd event has been completed, or the last user accesses the server for a period of time (typically 20 minutes), no one has access to the server.

What you want to define in the OnStart and OnEnd events of the Application object is to write the code in the Global.asa file (for an example below) and place the file in the root directory of the site (typically inetpub\wwwroot\)

Ii. overview of members of Session objects

The member of the session object has one more attribute than the Application object: Collection, property, method, event

Collection of ⒈session objects

Contents: There is no collection of all variables stored in a particular session object using the <OBJECT> element definition.

Staticobject: A collection of all the variables defined by the <OBJECT> element that are stored in the session object.

Example: The following assignment is available in the Default.asp

Session ("a") = "a"

Session ("B") =128

Session ("C") =false

Then there are contents sets

Session.Contents (1) = "A" can also be written as session.contents ("a") = "a"

Session.Contents (2) =128 ' can also be written as session.contents ("B") =128

Session.Contents (3) =false ' can also be written as session.contents ("C") =false

Properties of the ⒉session object

CodePage: readable/writable. Integral type. Defines the code page that is used to display the content of a page in a browser. The code page is the numeric value of the character set, and different languages use different code pages. For example, the ANSI code page is 1252, the Japanese code page is 932, and the Simplified Chinese code page is 936.

LCID: readable/writable. Integral type. Defines the page area identity that is sent to the browser. The LCID is an international standard abbreviation for uniquely identifying regions, for example, 2057 defines the currency symbol for the current region as "£".

SessionID: Read only. Long integral type. Returns the session identifier for this session. Each session is created with an identifier assigned automatically by the server. Depending on its value, you can determine who two users first access the server.

Timeout: readable/writable. Integral type. Defines a time-out limit in minutes for a session. If the user does not refresh or request any of the pages at this time, the session that the user produces will automatically end. The default value is 20.

The above attributes in the actual application of the role is not, and basically do not need to modify, these properties are no special place.

Methods of ⒊session objects

Contents.Remove ("Variable name"): Removes the specified variable from the Session.Contents collection

Contents.RemoveAll (): Deletes all variables in the Session.Contents collection

Abandon (): Ends the current user session and undoes the current sessions object.

The Contents.Remove ("variable name") and Contents.RemoveAll () method of the Session object are essentially no different from the Application object, to help understand, We can refer to the example above to change application to session. Here is the difference between contents.removeall () and abandon (), and executing both methods releases the current

All session variables for user sessions, except that Contents.RemoveAll () simply frees the value of the session variable and does not terminate the current session, while abandon () terminates the conversation, in addition to releasing the sessions variable Session_ OnEnd event, I hope you pay attention to the difference between the two.

Events for ⒋session objects

OnStart: Triggers when an ASP user session is generated, which occurs whenever any user requests a page on the server.

OnEnd: Triggered when an ASP user session ends, the event is triggered when the abandon () method or timeout is used.

These two events, like application's OnStart and OnEnd events, must be placed in Global.asa documents,
I will focus on the use of these four events.

Third, Global.asa

ASP's application and session objects embody features that are not in the other ASP's built-in objects-events. Each visitor accesses the server and triggers a OnStart event (the first visitor triggers both the application and session OnStart events, but application is preceded). A OnEnd event is triggered at the end of each visitor's session (the OnEnd event of the application and session is triggered at the end of the last guest conversation, but preceded by application).

OnStart and OnEnd These two events are commonly used in virtual communities to count online numbers, modify users ' online offline status, and so on. To define both events, you need to write the code in the Global.asa file and place the file in the root directory of the site (by default, \inetpub\wwwroot\). In addition, application and session objects specify other ASP built-in objects (Response, Request, Server, session ...) In addition to application objects in the OnEnd event. ) can not be used. Here is an example of how to use these two events with a virtual Community statistics online number.

File Description:

Global.asa is located in the D:\Inetpub\wwwroot\ directory

Default.asp is located in the D:\Inetpub\wwwroot\ directory, the virtual Community login page

Login.asp is located in the D:\Inetpub\wwwroot\ directory, used to detect user input username and password

Index.asp is located in the D:\Inetpub\wwwroot\ directory, the virtual community home

Bbs.mdb is located in the D:\Inetpub\wwwroot\ directory, the database where user information is stored

Database (ACCESS) Structure:

===bbs table = = =

ID user ID, long integer

Name username, text type

Code password, text type

Online status, yes/No

 
===global.asa===

Sub Application_OnStart

Application ("online") =0

End Sub

Sub Application_OnEnd

nd Sub

Sub Session_OnStart

End Sub

Sub Session_OnEnd

If Session.Contents ("pass") then ' to determine whether to be a logged-on user's Session_OnEnd

Application.Lock

Application ("Online") =application ("online")-1

Application.UnLock

End If

End Sub

==============

===login.asp===

... ' Password authentication, connect the database, detect the user entered the user name and password is correct

If password verification through then

Session ("name") =rs ("name")

Session ("id") =rs ("id")

Session ("Pass") =true

Else

Rs.close

Conn.close

Response.Write "Bad password! "

Response.End

End If

Application.Lock

Application ("Online") =application ("online") +1

Conn. Execute ("Update BBS set online=1 where id=" &session ("id")) ' sets the user's state to online

Application.UnLock

Rs.close

Conn.close

Response.Redirect "index.asp" ' Initialize data and jump to the home page of the community

===========

In this case, the application ("online") variable is used to record the number of online people who have logged in to the community, because once a user accesses the server regardless of whether the user is logged on, the OnStart event is generated, so Applicaiton (" Online ") plus one. Because whether or not the end of a logged-on user's session generates a OnEnd event (if a visitor accesses the server but does not log in to the community, and a OnEnd event occurs after his session ends), the Session_ The OnEnd event uses a sentence if statement to determine whether the logged in user's OnEnd event, if it is the number of people online minus one.

This is just a simple example of the number of people online, for a complete virtual community, it is not enough to count the number of users online, in this case there is a online field in the database to record the user's status, the user logged in, In the Login.asp will be online set to 1, but the user offline and did not set the online to 0, to improve it, it is necessary to modify the Session_OnEnd event, the event in the online set to 0.

===global. sas===

Sub Application_OnStart

Application ("online") =0

Set Application ("conn") =server.createobject ("ADODB. Connection ")

Application ("DB") =server.mappath ("\bbs.mdb") ' It is best to use absolute path \bbs.mdb here, described in detail below

End Sub

Sub Application_OnEnd

Set Application ("conn") =nothing

End Sub

Sub Session_OnStart

End Sub

Sub Session_OnEnd

If Session.Contents ("pass") then ' to determine whether to be a logged-on user's Session_OnEnd

Application ("Con"). Open = "Driver={microsoft Access driver (*.mdb)};d bq=" &application ("db")

Application.Lock

Application ("Online") =application ("online")-1

Application ("Con"). Execute ("Update friends set online=0 where id=" &session.contents ("id"))

Application.UnLock

Application ("Con"). Close

End If

End Sub

==============

At this point, the complete code is complete. Because the server object cannot be used in the application and session OnEnd events, the connection to the database and the physical address of the database on the server (d:\inetpub\wwwroot\ Bbs.mdb) is stored in the application variable and is processed in the Application_OnStart event in advance. Similarly, it is not possible to replace session.contents ("pass") with the session ("pass") in the Session_OnEnd event (with a detailed description below).

Four, two points worth noticing in the example of this article

The session.contents in the ⒈onend incident

Friends who have just started to contact Global.asa often take the Session_OnEnd event

If Session.Contents ("Pass") then written

If session ("pass") then,

In this case, the system will not prompt for an error, but will never perform the following then, because the session object is not allowed in the OnEnd event, but the session variable can be invoked with a collection of Session objects. Because IIS doesn't prompt for any error messages, I've wasted a lot of time on this. I hope everyone can heed this lesson!

In the ⒉application_onstart event, you should use an absolute address to obtain the physical address of the database in Server.MapPath to illustrate this problem, you can do an experiment: the above Application_OnStart incident

Application ("DB") =server.mappath ("\bbs.mdb") to read:

Application ("DB") =server.mappath ("Bbs.mdb")

Then create a test subdirectory under the D:\inetpub\wwwroot\ directory and write a temp.asp in the test directory.

====test.asp====

<%response.write application ("DB")%>

================

A copy of the temp.asp is placed in the root directory (d:\inetpub\wwwroot\). With Notepad open Global.asa, and then open two browser, browser a input address http://localhost/temp.asp, press ENTER, will be in the browser output:

D:\inetpub\wwwroot\bbs.mdb

Then, on the Notepad window, click the File menu, select Save (make global.asa changes, so that IIS restarts all services), and then enter the address http://localhost/test/temp.asp in browser B, press ENTER, and the browser output is:

D:\inetpub\wwwroot\test\bbs.mdb

The Global.asa file is placed in the root directory of the site, but if a relative address is used in the Server.MapPath, and the user who triggers the Application_OnStart event first accesses a page that is not part of the root directory, The physical address of the database will not be the desired result, and I hope you will be very careful.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.