Tuesday, September 23, 2008

I shot the session...

I was reading across a couple of old blogs recently about the need to kill a session immediately rather than waiting for it to timeout. If you are using J2EE sessions, the session will be orphaned when the browser is closed but the session still lives on until it eventually times out according to the time set for your application. There may be a need to clear out some of those sessions when you're sure they are orphans. Maybe you have a user that is logging in from another workstation and would like to clear out the other session so that you don't have the same user logged in twice. Whatever your reason, there is a way to immediately clear out the session and still have the onSessionEnd execute in your Application.cfc. Try this little piece of code:
<!--- get the session id by working with the session tracker --->
<cfset _sessionid = '74306b9b10b4c354a8db101f73246434611b'/>
<cfset killSession(application.applicationname,_sessionid)/>

<cffunction name="killSession" output="false"
access="public" returntype="void">
<cfargument name="appName" required="true" type="string" />
<cfargument name="sessionid" required="true" type="string" />

<cfset var st =
createobject("java","coldfusion.runtime.SessionTracker") />
<cfset st.cleanUp(arguments.appName,arguments.sessionid) />


If you do not have J2EE sessions enabled, you can call cleanUp(application.applicationName, _cfid, _cftoken).
Note: I haven't tested this one yet.

This will successfully remove that session. It will also execute any onSessionEnd code that you have to take care of any cleanup scripts that you have. This is an undocumented method of sessionTracker so use with caution knowing that things could change. I'm not sure if this works in versions before CF8. I would be interested in knowing, if someone would be so kind as to test it.



Michael van Leest said...

I tested it with the J2EE session variables disabled and tried to delete a session by sessionid, that failed. But when I tried it with cfid and cftoken, it worked like a charm!

Great info! Do you mind if use some of your code to build a full session manager cfc? I'll publish it on my (new to start) blog.

Teeps (Terry Palmer) said...

Have at it... that's why I posted it in the first place. If you haven't seen it yet, you may want to add the code documented here as well. http://cfteeps.blogspot.com/2008/09/undocumented-goodness.html

Ben Nadel said...

Very interesting stuff.

Troy said...


I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading.

Nice blog. I will keep visiting this blog very often.

Delphi development