Accessing Application and Session Scope in Coldfusion is generally straightforward but here is a rather smart way of doing it.The first step is to acces the CF runtime objects like below :-
[xml]
<cfset appTracker = createObject(“java”,“coldfusion.runtime.ApplicationScopeTracker”)/>
<cfset sessionTracker = createObject(“java”,“coldfusion.runtime.SessionTracker”)/>[/xml]
And this is how you get all the existing applications in CF runtime.
[xml]
<cfset apps = appTracker.getApplicationKeys() />
<cfset appsList = “”/>
<cfloop condition=“#apps.hasMoreElements()#”>
<cfset appName = apps.nextElement().toString()/>
<cfset appsList = listAppend(appsList, appName)/>
</cfloop>
<cfset appsList = listSort(appsList, ‘textNoCase’, ‘asc’)/>
<cfdump var = “#appsList#”>[/xml]
To access a particular Application scope :-
[xml]<cfset appName = appTracker.getApplicationScope("mysite") />
<cfdump var = "#appName#">[/xml]
Similarly, to get all existing Session keys :-
[xml]<cfset sessions = sessionTracker.getSessionKeys() />
<cfset sessionList = “” />
<cfloop condition=“#sessions.hasMoreElements()#”>
<cfset sessionList = listAppend(sessionList,sessions.nextElement())/>
</cfloop>
<cfdump var = “#sessionList#”>[/xml]
To get a Session Collection for a particular application :-
[xml]
<cfdump var = "#sessionTracker.getSessionCollection("mysite")#"/>[/xml]
To programmatically clear an application scope :-
[xml]
<cfset myApp = createObject(‘java’,’coldfusion.runtime.ApplicationScopeTracker’).init() />
<cfset myApp.getApplicationScope(mysite).cleanup() />[/xml]
For what version of CF is this code intended? I’ve got MX7.
Thanks.
Andy, This should work on MX7. Did you try it ?
Yes! Thank you. Does this open any security holes?
-Andy
Depends how you want to use it 🙂
Bear in mind, this wont work if the “Disable access to internal ColdFusion Java components ” is checked in CF adminstrator.
Hi Anuj,
I’m investigating a performance problem with our application and have seen this code (or very similar) used to count user sessions. Can you tell me if you think this code will effectively “keep-alive” the sessions retrieved from the tracker. The code is also calling methods to retrieve objects from the sessions rertieved from the tracker.
Hi Rob,
I have not used this code for keeping alive a session. But you shouldn’t have to use this code to count user sessions. This code is more of a server level thing to look at all the sessions and applications in a server instance.
What is the performance issue you facing?
Hello,
This is wonderful couple line of code. Clearing application scope is working, I’m trying to clear session scope for specific application, I tried cleanup() and remove() but with no success, can you give a little guide how to clear all sessions?