Macromedia Coldfusion MX 7 Web Application Construction Kit

Working with onSessionStart and onSessionEnd

Earlier in the chapter, we talked about how session variable can be enabled in the Application.cfc file and how handy they are for tracking information about your users. Another feature you may find handy is the ability to run code at both the beginning and end of a session. There are many ways this could be useful. Let's say you want to note when a user first entered your system. You could do this easily enough with:

<cfset SESSION.entered = now()>

This line of code is simple enough. However, you only want to run it once. You could use the isDefined function to check and see if the variable exists, but an even easier way would be to use the onSessionStart method of the Application.cfc file. This is a special method run only at the beginning of a user's session. Conversely, it may be handy to notice when a user's session end. In the past, this was (mostly) impossible in ColdFusion. But now that we have the powerful features provided by the Application.cfc file, we can handle scenarios like this. The onSessionEnd method is fired whenever a user's session times out. One simple use would be to log to a text file. Since we are noting when a user first comes to the system, we could log the total time the user was on the system. Listing 20.13 demonstrates an example of this. Be sure to save the file as Application.cfc.

Listing 20.13. Application4.cfcSupporting Session Events

<!--- Filename: Application.cfc Created by: Raymond Camden (ray@camdenfamily.com) Handles application events. ---> <cfcomponent output="false"> <cfset THIS.name="OrangeWhipSite_c20"> <cfset THIS.sessionManagement=true> <cfset this.sessiontimeout = createtimespan(0,0,0,10)> <cffunction name="onSessionStart" returnType="void"> <cfset SESSION.created = now()> </cffunction> <cffunction name="onSessionEnd" returnType="void"> <cfargument name="theSession" type="struct" required="true"> <cfset var duration = dateDiff("s",arguments.theSession.created,now())> <cflog file="#THIS.name#" text="Session lasted for #duration# seconds."> </cffunction> </cfcomponent>

Let's take a look at the two methods in this component. The onSessionStart method simply sets the created variable to the current time. The onSessionEnd method is going to use this variable. First noteinside the onSessionEnd method, you can't access the SESSION scope directly. Instead, the SESSION scope is passed in as an argument to the method. We create a variable to store the number of seconds the session was alive and then log this to a text file. You may have noticed the dramatically short sessiontimeout value. This was done so it would be easier to test. You don't have to just log to a file. You could also store the result to a database. This would be a very handy way to see how long users stick around on your web site.

Категории