Advanced ColdFusion Session Management

Published: {ts '2012-05-15 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/advanced-coldfusion-session-management/

Do you know how many sessions are currently in existence on your ColdFusion server instance? Do you know how many sessions exist for a particular application?

Well two years ago I had to answer this question in order to demonstrate why a 2 day session timeout was a really bad idea to another developer. Fortunately ColdFusion makes getting this information really easy. Not only that, you can expand on this technique to actually manipulate session instances other than your own. So lets get started..

Step 1: Get The Session Tracker Object

The first step is to create a java object instance of coldfusion.runtime.sessionTracker. Doing a dump of this object exposes all the available methods we can use to manipulate sessions.

The methods of interest to us are:

Step 2: Count All Sessions

To get a count of all the sessions is now a simple matter of calling the getSessionCount() method.

There are currently #sessionCount# sessions in existence on your server instance.

Note: You will note how the text reads "on your server instance". This is because you are getting a count of all sessions across all applications on the server instance, not just the application you are currently in. To get a count of the sessions in a particular application you have to do a little more work.

Step 3: Get The Session Collection For An Application

In order to count the number of sessions in a particular application we must first get the session collection using getSessionCollection(). This method takes in the string name of the application so provided we know its name we can get the session collection of any application on that server instance.

Dumping out this object returns a ColdFusion structure holding all the individual session structures for the application.

Step 4: Count The Number Of Session Instances For An Application

Getting the number of sessions for this particular application is now a simple matter of doing a structCount.

There are #sessionCountForApplication# sessions in existence for this application.

Step 5: Get And Manipulate Sessions

Finally we can use the getSession() method to access and manipulate each session using the key name for each session.

As an alternative to using the getSession() method, you can simply use normal session struct key referencing like so.

Note On Deleting Sessions

You would think that you could use this technique to delete a session instance but ColdFusion does not seem to allow that. However you can clear the contents of a session using structClear().

I hope this has been useful. Note that these techniques only scratch the surface of what you can do by leveraging ColdFusion's underlying java structure.