Is is possible to set a session variable in Application.cfc and then retrieve it from any of the application pages?

StackOverflow https://stackoverflow.com/questions/8051782

Question

With the example I have provided I would like for the index.cfm to display hello How can I do this?

Application.cfc

<cfcomponent>
    <cfset this.sessionManagement = true /> 

    <cffunction name="onSessionStart">
        <cfset SESSION.myVar = "hello">
    </cffunction>

</cfcomponent>

index.cfm

<html>
    <head>

    <title>Testing</title>

    </head>

    <body>
        <cfoutput>#SESSION.myVar#</cfoutput>
    </body>
</html>

I have discovered that when I add

<cfinvoke component="Application" method="onSessionStart">

to the index.cfm it works, however all the variable gets overridden every time the page is refreshed.

Was it helpful?

Solution

You need to give your application a name, eg:

<cfset this.name = "foo">

In your Application.cfc pseudo-constructor. Otherwise CF can't create an application, and so it cannot associate the session with the application.

OTHER TIPS

I'm assuming that you're new to ColdFusion or at least Application.cfc, but yes, onSessionStart is the basic way to initiate Session variables in your Application. Of course, they can be set/deleted/reset in any other page, so it might be good pratice to check for the existence of the variable in the SESSION scope before outputting it:

<cfif StructKeyExists(SESSION, "myVar")>
    <cfoutput>#SESSION.myVar#</cfoutput>
</cfif>

If the variable is not persisting, have you checked your Session Timeout setting (in ColdFusion Administrator)? You can set it there, which sets a default for all applications on the server, or you can set it right in Application.cfc:

THIS.SessionTimeout = CreateTimeSpan(0, 1, 0, 0); // One hour Session Timeout

Yes you can set variables in onSessionStart and use them in the application. The onSessionStart function only fires when a new session is created, so if it is being called on every request then your sessions are not persisting (your CFID / CFTOKEN, JSESSIONID) is not being passed on to subsequent requests. This is probably due to cookies being disabled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top