CFML Application.cfc

Mike's Notes

Pipi 9 is written in CFML.

Below is a collection of links gathered about using Application.cfc

The article below is an extract copied from the Adobe website. The full article is  named Defining the application and its event handlers in Application.cfc

Examples

Examples in script-based and tag-based syntax are at the end.

I use tag-based syntax, which makes it much easier to set up templates for Pipi.

MS Access

I always use MS Access for rapid visual development and database prototyping. It's fast, clean, and visually simple to use. Adding sample data or importing production config data is a dream. The SQL and cleaned, sorted data are then exported via DBeaver Community to PostgreSQL, MSSQL Express, etc., for production use by CFML.

I also often use an "empty" MS Access database as the front end for an MSSQL Server, etc., for form-based editing.

Resources

References

  • Reference

Repository

  • Home > Ajabbi Research > Library >
  • Home > Handbook > 

Last Updated

30/03/2026

CFML Application.cfc

By: Adobe
Adobe: 13/01/2022

The Application.cfc file defines application-wide settings and variables, and application event handlers:

  • Application-wide settings and variables include page processing settings, default variables, data sources, style settings, and other application-level constants.
  • Application event handlers are CFC methods that ColdFusion automatically executes when specific events occur during the lifetime of an application: application start and end, session start and end, request start, execution, and end, and exceptions.

Defining application-level settings and variables

When you create an application, you can set many application-wide properties and characteristics, including the following items:

  • Application name
  • Application properties, including Client-, Application-, and Session-variable management options
  • Page processing options
  • Default variables, data sources, style settings, and other application-level constants

For information on setting default variables, see Setting application default variables and constants in onApplicationStart  in this page.

Naming the application

Define the application and give it a name by setting the This.name variable in the Application.cfc initialization section, before the method definitions. By using a specific application name, you define a set of pages as part of the same logical application. 

ColdFusion supports unnamed applications, which are useful for ColdFusion applications that must interoperate with JSP tags and servlets. Consider creating an unnamed application only if your ColdFusion pages must share Application or Session scope data with existing JSP pages and servlets. You cannot have more than one unnamed application on a server instance. For more information on using unnamed applications, see Sharing data between ColdFusion pages and JSP pages or servlets in Interoperating with JSP pages and servlets.

Setting application properties

Specify application properties by setting  This scope variables  in the Application.cfc initialization code. (These are the same properties that you set in the  cfapplication  tag.) The following table lists  the This  scope variable that ColdFusion uses to set application properties and describes their uses.

Variable

Default

Description

applicationTimeout

Administrator value

Life span , as a real number of days, of the application, including all Application scope variables. Use the createTimeSpan function to generate this variable.

clientManagement

False

Whether the application supports Client scope variables.

clientStorage

Administrator value

Where Client variables are stored; can be  cookie , registry, or the name of a data source.

loginStorage

Cookie

Whether to store login information in the Cookie scope or the Session scope.

scriptProtect

Administrator Value

Whether to protect variables from cross-site scripting attacks.

sessionManagement

False

Whether the application supports Session scope variables.

sessionTimeout

Administrator Value

Life span , as a real number of days, of the user session, including all Session variables. Use the createTimeSpan function to generate this variable.

setClientCookies

True

Whether to send CFID and CFTOKEN cookies to the client browser.

setDomainCookies

False

Whether to use domain cookies for the CFID and CFTOKEN values used for client identification, and for Client scope variables stored using cookies. If False, ColdFusion uses host-specific cookies. Set to True for applications running on clusters.

The following example code from the top of an Application.cfc sets the application name and properties:

<cfcomponent>
<cfset This.name = "TestApplication">
<cfset This.clientmanagement="True">
<cfset This.loginstorage="Session">
<cfset This.sessionmanagement="True">
<cfset This.sessiontimeout="#createtimespan(0,0,10,0)#">
<cfset This.applicationtimeout="#createtimespan(5,0,0,0)#">

For more information on these settings, see cfapplication in the CFML Reference.

Setting page processing options

The  cfsetting  tag lets you specify the following page processing attributes to apply to all pages in your application:

Attribute

Use

showDebugOutput

Specifies whether to show debugging output. This setting cannot enable debugging if it is disabled in the ColdFusion Administrator. However, this option ensures that debugging output is not displayed, even if the Administrator enables it.

requestTimeout

Specifies the page request time-out. If ColdFusion cannot complete processing a page within the time-out period, it generates an error. This setting overrides the setting in the ColdFusion Administrator. Use this setting to increase the page time-out if your application or page frequently accesses external resources that are slow, such as external LDAP servers or web services providers.

enableCFOutputOnly

Disables output of text that is not included inside  cfoutput  tags. This setting helps ensure that extraneous text in your ColdFusion pages does not get displayed.

Often, you use the cfsetting tag on individual pages, but you can also use it in your Application.cfc file. For example, using it in multi-application environment to override the ColdFusion Administrator settings in one application.

You can place an application-wide cfsetting tag in the component initialization code, normally following the This scope application property settings, as the following example shows:

<cfscript>
This.name="MyAppl";
This.clientmanagement="True";
This.loginstorage="Session" ;
This.sessionmanagement="True" ;
This.sessiontimeout=CreateTimeSpan(0,0,1,0);
</cfscript>
<cfsetting showdebugoutput="No" enablecfoutputonly="No">

The cfsetting tag in this example affects all pages in an application. You can override the application-wide settings in the event methods, such as onRequestStart, or on individual ColdFusion pages.

Using application event handlers

The following table describes the application event CFC methods that you can implement, including when they are triggered.

Method

When run

onApplicationStart

The application first starts: when the first request for a page is processed or the first CFC method is invoked by an event gateway instance, Flash Remoting request, or a web service invocation. This method is useful for setting application-wide (Application scope) variables, such as the names of data sources.

onApplicationEnd

The application ends: when the application times out or the server shuts down.

onSessionStart

A new session is created as a result of a request that is not in an existing session, including ColdFusion event gateway sessions. The application must enable sessions for this event to happen.

onSessionEnd

A session time-out setting is reached. This event is not triggered when the application ends or the server shuts down.

onRequestStart

ColdFusion receives any of the following: a request, an HTTP request (for example, from a browser), a message to an event gateway, a SOAP request, or a Flash Remoting request.

onRequest

The onRequestStart event has completed. This method acts as a filter for the requested page content.

onRequestEnd

All pages and CFCs in the request have been processed: equivalent to the OnRequestEnd.cfm page.

onMissingTemplate

When ColdFusion receives a request for a nonexistent page.

onError

When an exception occurs that is not caught by a try/catch block.

When ColdFusion receives a request, it instantiates the Application CFC and runs the Application.cfc code in the following order:

  1. CFC initialization code at the top of the file
  2. onApplicationStart, if not run before for this application
  3. onSessionStart, if not run before for this session
  4. onRequestStart
  5. onRequest, or the requested page if there is no onRequest method
  6. onRequestEnd

The following methods are triggered by specific events:

  • onApplicationEnd
  • onSessionEnd
  • onMissingTemplate
  • onError

The onApplicationEnd and onSessionEnd methods do not execute in the context of a page request, so they cannot access request variables or display information to the user. The onMissingTemplate method is triggered when a URL specifies a CFML page that does not exist. The OnError method does not always execute in the context of a request; use its Event argument to determine the context.

Managing the application with Application.cfc

Use the onApplicationStart and onApplicationEnd methods to configure and manage the application; that is, to control resources that are used by multiple pages and requests and must be consistently available to all code in your application. Such resources include data sources, application counters such as page hit variables, or style information for all pages.

The onApplicationStart method executes when ColdFusion gets the first request for a page in the application after the server starts. The onApplicationEnd method executes when the application server shuts down or if the application is inactive for the application time-out period.

The following are some of the ways you use these methods. For more information, see entries for onApplicationStart and onApplicationEnd in the CFML Reference.

Defining application utility functions

Functions that you define in Application.cfc and do not place in a shared scope are, by default, available only to other methods in the CFC. 

If your Application.cfc implements the onRequest method, any utility functions that you define in Application.cfc are also directly available in to the target page, because Application.cfc and the target page share the Variables scope.

If your application requires utility functions that are used by multiple pages, not just by the methods in Application.cfc, and you do not use an onRequest method, Adobe recommends that you place them in a separate CFC and access them by running that CFC. As with other ColdFusion pages, Application.cfc can access any CFC in a directory path that is configured on the ColdFusion Administrator Mappings page. Therefore, use this technique to share utility functions across applications.

If your Application.cfc defines utility functions that you want available on request pages and does not use an onRequest method, explicitly place the functions in a ColdFusion scope, such as the Request scope, as the following code shows:

<!--- Function definition goes here. --->
</cffunction>
<cffunction name="OnRequestStart">
<!--- OnRequestStart body goes here --->
<cfset Request.theFunctionName=This.theFunctionName>
</cffunction>

On the request page, you would include the following code:

<cfset myVar=Request.theFunctionName(Argument1...)>

Functions that you define in this manner share the This scope and Variables scope with the Application.cfc file for the request.

Setting application default variables and constants in onApplicationStart

You can set default variables and application-level constants in Application.cfc. For example, you can do the following:

  • Specify a data source and ensure that it is available
  • Specify domain name
  • Set styles, such as fonts or colors
  • Set other application-level variables

You do not have to lock Application scope variables when you set them in the Application.cfc onApplicationStart method.

For details on implementing the onApplicationStart method, see onApplicationStart in the CFML Reference.

Using the onApplicationEnd method

Use the onApplicationEnd method for any clean-up activities that your application requires when it shuts down, such as saving data in memory to a database, or to log the application end. You cannot use this method to display data on a user page, because it is not associated with any request. The application ends, even if this method throws an exception. An application that is used often is unlikely to execute this method, except when the server is shut down. 

For details on implementing the onApplicationEnd method, see onApplicationEnd in the CFML Reference.

Managing sessions in Application.cfc

Use the onSessionStart and onSessionEnd methods to configure and manage user sessions; that is, to control resources that are used by multiple pages while a user is accessing your site from during a single browser session. The session begins when a user first requests a page in your  application,  and ends when the session times out. For more information on Session scope and Session variables, see Using Persistent Data and Locking.

Session resources include variables that store data that is needed throughout the session, such as account numbers, shopping cart contents, or CFCs that contain methods and data that are used by multiple pages in a session.

Note

Do not include the cflogin tag or basic login processing in the onSessionStart method, as the code executes only at the start of the session; it cannot handle user logout, and cannot fully ensure security.

Using the onSessionStart method

This method is useful for initializing session data, such as user settings or shopping cart contents, or for tracking the number of active sessions. You do not need to lock the Session scope when you set session variables in this method.

For more information, see the onSessionStart entry in the CFML Reference.

Using the onSessionEnd method

Use this method for any clean-up activities when the session ends. (For information on ending sessions, see Ending a session in Configuring and using session variables.) For example, you can save session-related data, such as shopping cart contents or information about whether the user has not completed an order, in a database, or you can log the end of the session to a file. You cannot use this method to display data on a user  page,  because it is not associated with a request.

Note

Sessions do not end, and the onSessionEnd method is not called when an application ends. For more information, see the  onSessionEnd  entry in the CFML Reference.

ColdFusion provides three methods for managing requests: onRequestStart, onRequest, and onRequestEnd. ColdFusion processes requests, including these methods, as follows:

  1. ColdFusion always processes  onRequestStart  at the start of the request.
  2. If you implement an onRequest method, ColdFusion processes it; otherwise, it processes the requested page. If you implement an onRequest method, explicitly call the requested page in your onRequest method.
  3. ColdFusion always processes onRequestEnd at the end of the request.

Note

When using cfabort, cflocation, or cfcontent tags, the OnAbort method is invoked instead of OnRequestEnd.

You can use each of the Application.cfc request methods to manage requests as follows:

Using the onRequestStart method

This method runs at the beginning of the request. It is useful for user authorization (login handling), and for request-specific variable initialization, such as gathering performance statistics.

If you use the onRequestStart method and do not use the onRequest method, ColdFusion automatically processes the request when it finishes processing the onRequestStart code.

Note

If you do not include an onRequest method in Application.cfm file, the onRequestStart method does not share a Variables scope with the requested page, but it does share Request scope variables.

For more information, see the entry for onRequestStart in the CFML Reference

User authentication

When an application requires a user to log in, include the authentication code, including the  cflogin  tag or code that calls this tag, in the onRequestStart method. Doing so ensures that the user is authenticated at the start of each request. For detailed information on security and creating logins, see Securing Applications For an example that uses authentication code generated by the Adobe Dreamweaver CF Login Wizard, see onRequestStart in the CFML Reference.

Using the onRequest method

The onRequest method differs from the onRequestStart method in one major way: the onRequest method intercepts the user's request. This difference has two implications:

  • ColdFusion does not process the request unless you explicitly call it, for example, by using a  cfinclude  tag. This behavior lets you use the onRequest method to filter requested page content or to implement a switch that determines the pages or page contents to be displayed.
  • When you use  cfinclude  to process  request , the CFC instance shares the Variables scope with the requested page. As a result, any method in the CFC that executes can set the page's Variables scope variables, and the onRequestEnd method can access any Variable scope values that the included page has set or changed. Therefore, for example, the onRequestStart or onRequest method set variables that are used on the page.

To use this method as a filter, place the  cfinclude  tag inside a  cfsavecontent  tag, as the following example shows:

<cfargument name = "targetPage" type="String" required=true/>
<cfsavecontent variable="content">
<cfinclude template=#Arguments.targetPage#>
</cfsavecontent>
<cfoutput>
#replace(content, "report", "MyCompany Quarterly Report", "all")#
</cfoutput>
</cffunction>

For more information, see the entry for onRequest in the CFML Reference

Using the onRequestEnd method

You use the onRequestEnd method for code that should run at the end of each request. (In ColdFusion versions through ColdFusion MX 6.1, you would use the OnRequestEnd.cfm page for such code). Typical uses include displaying dynamic footer pages. For an example, see onSessionEnd in the CFML Reference.

Note

If you do not include an onRequest method in Application.cfm file, the onRequestEnd method does not share a Variables scope with the requested page, but it does share Request scope variables.

For more information, see the entry for onRequestEnd in the CFML Reference.

Handling errors in Application.cfc

The following sections briefly describe how you to handle errors in Application.cfc. For more information on error pages and error handling, see Handling Errors For details on implementing the onError method, see onError in the CFML Reference.

Application.cfc error handling techniques

Application.cfc handles errors in any combination of the following ways:

  • Use try/catch error handling in the event methods, such as onApplicationStart or onRequestStart, to handle exceptions that happen in the event methods.
  • Implement the onError method. This method receives all exceptions that are not directly handled by try/catch handlers in CFML code. The method can use the  cfthrow  tag to pass any errors it does not handle to ColdFusion for handling.{{}}
  • Use  cferror  tags in the application initialization code following the  cfcomponent  tag, typically following the code that sets the application's This scope variables . These tags specify error processing if you do not implement an onError  method, or if the onErrormethod throws an error. You could implement an application-specific validation error handler, for example, by placing the following tag in the CFC initialization code:
    <cferror type="VALIDATION" template="validationerrorhandler.cfm">
  • The ColdFusion default error mechanisms handle any errors that are not handled by the preceding techniques. These mechanisms include the site-wide error handler that you specify in the ColdFusion Administrator and the built-in default error pages.

    These techniques let you include application-specific information, such as contact information or application or version identifiers, in the error message, and let you display all error messages in the application in a consistent manner. You use Application.cfc to develop sophisticated application-wide error-handling techniques, including error-handling methods that provide specific messages, or use structured error-handling techniques.

Note

The onError method catches errors that occur in the onSessionEnd and onApplicationEnd application event methods. It does not display messages to the user, however, because there is no request context. The onError function logs errors that occur when the session or application ends

Handling server-side validation errors in the onError method

Server-side validation errors are actually ColdFusion exceptions; as a result, if your application uses an onError  method, this method gets the error and must handle it or pass it on to ColdFusion for handling.

To identify a server-side validation error, search the Arguments.Exception.StackTrace field for coldfusion .filter.FormValidationException. You can then handle the error directly in your onError routine, or throw the error so that either the ColdFusion default validation error page or a page specified by an  cferror  tag in your Application.cfc initialization code handles it.

Example: error Handling with the onError method

The following Application.cfc file has  an onError  method that handles errors as follows:

  • If the error is a server-side validation error, the onError method throws the error for handling by ColdFusion, which displays its standard validation error message.
  • For any other type of exception, the onError method displays the name of the event method in which the error occurred and dumps the exception information. In this example, because you generate errors on the CFM page only, and not in  a Application.cfc  method, the event name is always the empty string.

<cfset This.name = "BugTestApplication">
<cffunction name="onError">
<!--- The onError method gets two arguments:
An exception structure, which is identical to a cfcatch variable.
The name of the Application.cfc method, if any, in which the error
happened.
<cfargument name="Except" required=true/>
<cfargument type="String" name = "EventName" required=true/>
<!--- Log all errors in an application-specific log file. --->
<cflog file="#This.Name#" type="error" text="Event Name: #Eventname#" >
<cflog file="#This.Name#" type="error" text="Message: #except.message#">
<!--- Throw validation errors to ColdFusion for handling. --->
<cfif Find("coldfusion.filter.FormValidationException",
Arguments.Except.StackTrace)>
<cfthrow object="#except#">
<cfelse>
<!--- You can replace this cfoutput tag with application-specific
error-handling code. --->
<cfoutput>
<p>Error Event: #EventName#</p>
<p>Error details:<br>
<cfdump var=#except#></p>
</cfoutput>
</cfif>
</cffunction>
</cfcomponent>

To test this example, place a CFML page with the following code in the same page as the Application.cfc file, and enter valid and invalid text in the text input field.

This box does Integer validation:
<cfinput name="intinput" type="Text" validate="integer" validateat="onServer"><br>
Check this box to throw an error on the action page:
<cfinput type="Checkbox" name="throwerror"><br>
<cfinput type="submit" name="submitit">
</cfform>
<cfif IsDefined("form.fieldnames")>
<cfif IsDefined("form.throwerror")>
<cfthrow type="ThrownError" message="This error was thrown from the bugTest action page.">
<cfelseif form.intinput NEQ "">
<h3>You entered the following valid data in the field</h3>
<cfoutput>#form.intinput#</cfoutput>
</cfif>
</cfif>

Note

For more information on server-side validation errors, see Validating data.

Example: a complete Application.cfc

The following example is a simplified Application.cfc file that illustrates the basic use of all application event handlers:

<cfset This.name = "TestApplication">
<cfset This.Sessionmanagement=true>
<cfset This.Sessiontimeout="#createtimespan(0,0,10,0)#">
<cfset This.applicationtimeout="#createtimespan(5,0,0,0)#">

<cffunction name="onApplicationStart">
<cftry>
<!--- Test whether the DB that this application uses is accessible
by selecting some data. --->
<cfquery name="testDB" dataSource="cfdocexamples" maxrows="2">
SELECT Emp_ID FROM employee
</cfquery>
<!--- If we get database error, report it to the user, log the error
information, and do not start the application. --->
<cfcatch type="database">
<cfoutput>
This application encountered an error.<br>
Please contact support.
</cfoutput>
<cflog file="#This.Name#" type="error"
text="cfdocexamples DB not available. message: #cfcatch.message#
Detail: #cfcatch.detail# Native Error: #cfcatch.NativeErrorCode#">
<cfreturn False>
</cfcatch>
</cftry>
<cflog file="#This.Name#" type="Information" text="Application Started">
<!--- You do not have to lock code in the onApplicationStart method that sets Application scope variables. --->
<cfscript>
Application.availableResources=0;
Application.counter1=1;
Application.sessions=0;
</cfscript>
<!--- You do not need to return True if you don't set the cffunction returntype attribute. --->
</cffunction>

<cffunction name="onApplicationEnd">
<cfargument name="ApplicationScope" required=true/>
<cflog file="#This.Name#" type="Information"
text="Application #ApplicationScope.applicationname# Ended">
</cffunction>


<cffunction name="onRequestStart">
<!--- Authentication code, generated by the Dreamweaver Login Wizard,
makes sure that a user is logged in, and if not displays a login page. --->
<cfinclude template="mm_wizard_application_include.cfm">
<!--- If it's time for maintenance, tell users to come back later. --->
<cfscript>
if ((Hour(now()) gt 1) and (Hour(now()) lt 3)) {
WriteOutput("The system is undergoing periodic maintenance.
Please return after 3:00 AM Eastern time.");
return false;
} else {
this.start=now();
}
</cfscript>
</cffunction>

<cffunction name="onRequest">
<cfargument name = "targetPage" type="String" required=true/>
<cfsavecontent variable="content">
<cfinclude template=#Arguments.targetPage#>
</cfsavecontent>
<!--- This is a minimal example of an onRequest filter. --->
<cfoutput>
#replace(content, "report", "MyCompany Quarterly Report", "all")#
</cfoutput>
</cffunction>

<!--- Display a different footer for logged in users than for guest users or 
users who have not logged in. --->

<cffunction name="onRequestEnd">
<cfargument type="String" name = "targetTemplate" required=true/>
<cfset theAuthuser=getauthuser()>
<cfif ((theAuthUser EQ "guest") OR (theAuthUser EQ ""))>
<cfinclude template="noauthuserfooter.cfm">
<cfelse>
<cfinclude template="authuserfooter.cfm">
</cfif>
</cffunction>

<cffunction name="onSessionStart">
<cfscript>
Session.started = now();
Session.shoppingCart = StructNew();
Session.shoppingCart.items =0;
</cfscript>
<cflock timeout="5" throwontimeout="No" type="EXCLUSIVE" scope="SESSION">
<cfset Application.sessions = Application.sessions + 1>
</cflock>
<cflog file="#This.Name#" type="Information" text="Session:
#Session.sessionid# started">
</cffunction>

<cffunction name="onSessionEnd">
<cfargument name = "SessionScope" required=true/>
<cflog file="#This.Name#" type="Information" text="Session:
#arguments.SessionScope.sessionid# ended">
</cffunction>

<cffunction name="onError">
<cfargument name="Exception" required=true/>
<cfargument type="String" name = "EventName" required=true/>
<!--- Log all errors. --->
<cflog file="#This.Name#" type="error" text="Event Name: #Eventname#">
<cflog file="#This.Name#" type="error" text="Message: #exception.message#">
<!--- Some exceptions, including server-side validation errors, do not
generate a rootcause structure. --->
<cfif isdefined("exception.rootcause")>
<cflog file="#This.Name#" type="error"
text="Root Cause Message: #exception.rootcause.message#">
</cfif>
<!--- Display an error message if there is a page context. --->
<cfif NOT (Arguments.EventName IS onSessionEnd) OR
(Arguments.EventName IS onApplicationEnd)>
<cfoutput>
<h2>An unexpected error occurred.</h2>
<p>Please provide the following information to technical support:</p>
<p>Error Event: #EventName#</p>
<p>Error details:<br>
<cfdump var=#exception#></p>
</cfoutput>
</cfif>
</cffunction>

</cfcomponent>

Script-based syntax example

An Application.cfc file is a special ColdFusion Component used to define application-level settings and event handlers that manage the lifecycle of a CFML application.

Below is a modern, script-based example of an Application.cfc file.

component {
    // 1. Application Settings
    this.name = "MyAwesomeApp_" & hash(getCurrentTemplatePath()); // Unique app name
    this.applicationTimeout = createTimeSpan(30, 0, 0, 0);         // 30 days
    this.sessionManagement = true;                                 // Enable sessions
    this.sessionTimeout = createTimeSpan(0, 0, 30, 0);             // 30 minutes
    this.setClientCookies = true;                                  // Use CFID/CFTOKEN cookies

    // 2. Lifecycle Events

    // Runs once when the application first starts
    public boolean function onApplicationStart() {
        application.version = "1.0.0";
        application.startedAt = now();
        return true; 
    }

    // Runs when a new user session begins
    public void function onSessionStart() {
        session.started = now();
        session.cart = [];
    }

    // Runs at the very start of every page request
    public boolean function onRequestStart(required string targetPage) {
        // Useful for security checks or global variables
        request.startTime = getTickCount();
        
        // Example: Force app re-init during development
        if (structKeyExists(url, "reinit")) {
            onApplicationStart();
            onSessionStart();
        }
        return true;
    }

    // Handles the actual request processing
    public void function onRequest(required string targetPage) {
        include arguments.targetPage;
    }

    // Runs if an unhandled error occurs in the application
    public void function onError(any exception, string eventName) {
        // You can log errors or redirect to a custom error page here
        writeLog(type="Error", text="Error in #arguments.eventName#: #arguments.exception.message#");
        include "error.cfm";
    }
}

Tag-based syntax example

If you prefer the traditional tag-based syntax (using <cfset> and <cffunction>), here is how that same structure looks. This style is still very common in older or "legacy" ColdFusion codebases.

<cfcomponent>
    <!--- 1. Application Settings --->
    <cfset this.name = "MyTaggedApp">
    <cfset this.sessionManagement = true>
    <cfset this.sessionTimeout = createTimeSpan(0, 0, 30, 0)>
    <cfset this.setClientCookies = true>

    <!--- 2. Lifecycle Events --->

    <!--- Runs once when the application first starts --->
    <cffunction name="onApplicationStart" returnType="boolean" output="false">
        <cfset application.version = "2.1.0">
        <cfreturn true>
    </cffunction>

    <!--- Runs when a new user session begins --->
    <cffunction name="onSessionStart" returnType="void" output="false">
        <cfset session.started = now()>
    </cffunction>

    <!--- Runs at the start of every page request --->
    <cffunction name="onRequestStart" returnType="boolean" output="false">
        <cfargument name="targetPage" type="string" required="true">
        
        <!--- Example: Force re-init if 'reinit' is in the URL --->
        <cfif structKeyExists(url, "reinit")>
            <cfset onApplicationStart()>
        </cfif>
        
        <cfreturn true>
    </cffunction>

    <!--- Handles the actual request processing --->
    <cffunction name="onRequest" returnType="void">
        <cfargument name="targetPage" type="string" required="true">
        
        <!--- This is where the requested .cfm file is actually executed --->
        <cfinclude template="#arguments.targetPage#">
    </cffunction>

    <!--- Error handling --->
    <cffunction name="onError" returnType="void" output="true">
        <cfargument name="exception" type="any" required="true">
        <cfargument name="eventName" type="string" required="true">
        
        <h2>An error occurred!</h2>
        <p>Details: <cfoutput>#arguments.exception.message#</cfoutput></p>
    </cffunction>
</cfcomponent>

Adobe Application Variables

The scope for the Application.cfc file contains several built-in variables, which correspond to the attributes that you set in the cfapplication tag. You set the values of these variables in the CFC initialization code, before you define the CFC methods. You can access the variables in any method.

Note: Although Windows is case-insensitive, you must always start the Application.cfc filename with an uppercase A. Both application.cfc and Application.cfc are reserved words.

Note: If your application has an Application.cfc, and an Application.cfm or onRequestend.cfm page, ColdFusion ignores the CFM pages

The following table briefly describes the variables that you can set to control the application behavior. For more details, see the cfapplication tag.

Variable Default Description
name no name The application name. If you do not set this variable, or set it to the empty string, your CFC applies to the unnamed application scope, which is the ColdFusion J2EE servlet context. For more information on unnamed scopes see Integrating JSP and servlets in a ColdFusion application in Interoperating with JSP pages and servlets in the Developing ColdFusion Applications.
applicationTimeout Administrator value Life span, as a real number of days, of the application, including all Application scope variables. Use the CFML CreateTimeSpan function to generate this variable's value.
authcookie.disableupdate False Disable update of cfauthorization cookie using cfcookie or cfheader tag
authcookie.timeout -1 Auth Cookie age in days. The cookie doesn't times out.
authcookie.samesite   Valid values are Struct, Lax, or None.
cache.useInternalQueryCache false If true, ColdFusion will store cached queries in the old non-cool non-Ehcache version of the cache.
cache.querysize Administrator value Maximum number of queries that can be cached. To be clear, this refers to automatic caching via cachedWithin and cachedAfter in the cfquery/queryExecute tag/function. You can store as many queries as you would like using cachePut. Well, as many as your RAM will allow. Be sensible, people.
chartStyleDirectory   Application specific chart styles directory.
clientManagement no
  • yes: enables client variables.

  • no

clientStorage Administrator value Where Client variables are stored; can be cookie, registry, or the name of a data source.
customtagpaths Administrator value Contains ColdFusion custom tag paths. It is a comma delimited list with absolute path.To use this variable, select the Enable Per App Settings option in the Administrator Server > Settings page.The settings that you define here take precedence over the custom tag paths defined in the Administrator Server Settings > Mappings page for the current application.
googleMapKey   The Google Maps API key required to embed Google Maps in your web pages.
datasource   Name of the data source from which the query retrieves data.
datasources   Struct of structs defining datasources.You can use this variable to define a datasource specific to the application . This does not register/update a datasource in ColdFusion Administrator.
loginStorage cookie Whether to store login information in the Cookie scope or the Session scope.
mappings Administrator value A structure that contains ColdFusion mappings. Each element in the structure consists of a key and a value. The logical path is the key and the absolute path is the value. To use this variable, select the Enable Per App Settings option in the Administrator Server Settings > Settings page.The mappings that you define here take precedence over the mappings defined in the Administrator Server Settings > Mappings page for the current application.
passArrayByReference False Arrays will be passed by reference instead of by value for this application.
restSettings.cfclocation   To publish the CFCs only in a particular location, provide comma-separated list of directories where the REST CFCs are located. The directory paths can be absolute or relative.If not set, all the CFCs from the application root are published.
restSettings.skipCFCWithError   When an error occurs, continue publishing, ignoring the CFC that has caused the exception.If true, the CFC with error is ignored and the rest of the CFCs are published. By default it is false.If set to false, in case of an error, the application itself is not published. But other registered application are published.If an error occurs during application startup, the error is printed in console.Each application has separate log files for logging the issues.
restSettings.restEnabled False If true, then ColdFusion searches the directory containing a set of REST-enabled CF components. 
restSettings.autoRegister False Enable auto registration of an application.
restSettings.useHost False Specifies the host name. If true, then the host name is parsed from the URL.
restSettings.host  

Explicitly naming the hostname will make the host name. If the host name is not mentioned, then the usehost name will be defaulted.

restSettings.serviceMapping   If not specified, then the application defined in this.name is taken as default.
restSettings.isDefault False If true, application will be made as default app.
scriptprotect None

If true, it adds protection from external scripts and cross-site scripting. Valid values are:

  • Form
  • URL
  • Cookie
  • CGI

The flag protects from the following:

  • object
  • embed
  • script
  • applet
  • meta

The feature is a set of regular expressions located in lib/neo-security.xml that replaces the tags: object, embed, script, applet, and meta with the tag name InvalidTag, when they are passed as input to the Form, URL, CGI, and Cookie scopes.

sessioncookie.httponly True Specify whether session cookies have to be set as httponly or not. i.e. accessible only to Http requests
sessioncookie.secure False Specify whether session cookies have to be set as secure or not. i.e. returned on any type of connection or only secured (https) connections
sessioncookie.domain   Domain for which the cookie should be set. This should match exactly with the domain, with which application would be accessed
sessioncookie.timeout 30 years
Session Cookie age in days. You can also assign -1 to this value, while 0 is invalid.
sessioncookie.disableupdate False Disable update of cfid and cftoken cookie using cfcookie or cfheader tag
serverSideFormValidation yes Whether to enable validation on cfform fields when the form is submitted.
sessionManagement no Whether the application supports Session scope variables.
sessionTimeout Administrator value Life span, as a real number of days, of the user session, including all Session variables. Use the CFML CreateTimeSpan function to generate this variable's value.
setClientCookies True Whether to send CFID and CFTOKEN cookies to the client browser.
setDomainCookies False Whether to set CFID and CFTOKEN cookies for a domain (not just a host).
security.antisamypolicy   Specify the location of antisamy file to be used when no antisamy policy file is passed to the getSafeHTML or isSafeHTML functions. The policy file can be relative to the Application CFC path or an absolute path can be provided.
compileextforinclude   Specify the list of allowed file extensions as a comma-separated list for the cfinclude tag. Specifying a wildcard * in the list makes any file included using the cfinclude tag to be compiled. If any file included using the cfinclude tag is not found in this list, their content will be statically included. By default, files with the cfm and cfml extensions are always compiled irrespective of this setting.
strictnumbervalidation  

True/False. Default is true. The IsValid function for the integer and numeric types allowed the currency symbols at the start and commas inside the number.

In ColdFusion 11, the isValid function behaves in a different way. Setting strictnumbervalidation to false makes the isValid function to behave in a way just like in the previous versions (ColdFusion 10 or earlier). Note that this setting also changes the behavior of the following tags:

secureJSON Administrator value A Boolean value that specifies whether to add a security prefix in front of the value that a ColdFusion function returns in JSON-format in response to a remote call. The default value is the value of the Prefix serialized JSON setting in the Administrator Server Settings > Settings page (which defaults to false). You can override this value in the cffunction tag.For more information see Improving security in Ajax programming rules and techniques in the Developing ColdFusion Applications.
secureJSONPrefix Administrator value The security prefix to put in front of the value that a ColdFusion function returns in JSON-format in response to a remote call if the secureJSON setting is true. The default value is the value of the Prefix serialized JSON setting in the Administrator Server Settings > Settings page (which defaults to //, the JavaScript comment character).For more information see Improving security in Ajax programming rules and techniques in the Developing ColdFusion Applications.
serialization.preservecaseforstructkey False Boolean that determines if case for struct keys should be preserved when serializing a struct to JSON.
serialization.serializequeryas row Determines how queries should be serialized to JSON. Possible values are row, column, and struct.
serialization.preserveCaseForQueryColumn false If true, column case will be preserved.
sessioncookie.samesite 
  Valid values are Strict, Lax, or None.
welcomeFileList  

A comma-delimited list of names of files. Tells ColdFusion not to call the onMissingTemplate method if the files are not found. Use this variable to prevent ColdFusion from invoking the onMissingTemplate handler if all of the following items are true:

  • Your web server (for example, web.xml file) has a welcome file list with CFML pages such as index.cfm that it tries to run if a URL specifies a path ending in a directory.
  • The web server sends a request for CFML pages the welcome list to ColdFusion without first determining if the page exists.
  • You want to support directory browsing in directories that do not have any of the files on the welcome file list.
    You specify this variable only if the Application.cfc file also specifies an onMissingTemplate handler. It must have the same list of files as your web.xml welcome file list.Note: You do not need to use the welcomeFileList variable with most "pure" web servers, such as Apache. The welcomeFileList variable has to be used with most integrated web and application servers.
smtpServersettings   A struct that contains the following values: server, username, and password.If no value is specified, takes the value in the administrator.
sameformfieldsasarray false If the form fields have the same name, ColdFusion converts the form fields as an array instead of a list. To do this, in the Application.cfc, specify the following: this.sameformfieldsasarray = "true". Note: The empty string values will be preserved only if this is set to true.
timeout   This number represents how long an individual request can take. Timeout set using overrides the timeout in the Application.cfc using this.timeout="".
debuggingIPAddresses   A list of IP addresses that need debugging.
enablerobustexception   Overrides the default administrator settings. It does not report compile-time exceptions.
javaSettings   A structure allowing you to specify Java class paths to be made available to your code. Valid keys are: loadPaths (an array of paths to include when searching for Java libraries), loadColdFusionClassPath (a boolean indicating if the default class path should be used, defaults to false), and reloadOnChange (a boolean indicating if the classpaths should be reloaded when they change, the default is false).
javasettings.watchInterval   Specifies the time interval in seconds after which to verify any change in the class files or JAR files. This attribute is applicable only if the reloadOnChange attribute is set to true. The default value is 60 seconds.
javasettings.watchExtensions   Specifies the extensions of the files to monitor for changes. By default, only .class and .jar files are monitored.
searchimplicitscopes False

Allows you to enable or disable searching for an un-scoped variable in implicit scopes.

NOTE: In ColdFusion (2023 release) Update 7, the default value for this flag is changed to FALSE.

serialization.structmetadata   Set the data type info for a struct value. For example, if this.serialization.structmetadata = {zipcode="String"};, you need not define the data type for zipcode for the struct that contains this key. If you define the datatype for zipcode in the struct itself, then the defined datatype at struct level takes priority over the one defined in Application.cfc.
enableNullSupport false Allows you to enable or disable support for NULL variables. Possible values are true or false.
cache.engine ehcache

Specified the cache engine to be used. You can use the following engines:

  • Ehcache
  • JCS
  • Memcached
  • Redis
cache.configFile   Path to the properties file of the caching engine.
restSettings.generateRESTDoc false If true, then ColdFusion server generates Swagger doc automatically.
blockedExtForFileUpload   A comma-separated list of file extensions for the files that must be blocked for uploading.
useJavaAsRegexEngine false If true, then Java is used as regex engine over the default engine.
timeZone
  If true, if you execute any date/time function, the time zone returned will be the same as set in this flag.

Form fields with same name

Assume that the form fields have same name. In this case, ColdFusion converts the form fields as an array instead of a list.To do this, in the Application.cfc, specify the following: this.sameformfieldsasarray = "true".The default value is false.

Note

Application.cfc is unable to resolve nested cfincludes from outside the directory where te file resides. To resolve this, add the flag -Dcoldfusion.application.recur_resolve.include=true needs be added in jvm.config.

Enhancements made in ColdFusion (2021 release)

  • this.timeZone

There is a new flag, this.timeZone, which you can set it to any valid time zone. After setting the time zone, if you execute any date/time function, the time zone returned will be the same as set in Application.cfc. For example,

Application.cfc


component {
    this.timeZone="US/Pacific"
}
timezone.cfm
<cfscript>
    writeOutput("The time at the configured time zone is: " & now())
</cfscript>
MongoDb settings
this.datasources = { 
    "local"= { 
        type="mongodb" 
    }, 
    "mymongodb"= { 
        type="mongodb", 
        host="mongodb://10.192.217.184:27017/", 
        "init"= true 
    } 
}

AWS Cloud Features (SQS, SNS, S3, DynamoDB)


component { 
 
   function OnApplicationStart() { 
      application.awsCred = { 
         "credentialAlias" : "<alias name>", 
         "vendorName" : "AWS", 
         "region" : "<region name>", 
         "secretAccessKey" : "<AWS Secret>", 
         "accessKeyId" : "<AWS Key>" 
      }; 
 
      application.awsConf = { 
         "serviceName" = "<Service name>", 
 
         "alias" : “<alias name>”, 
 
         "clientOverrideConfig": { 
 
            "apiCallAttemptTimeout": "<timeout>" 
 
         } 
 
      }; 
 
      application.accountKey = "<Account Key>"; 
   } 
}

SAML

Manual Configuration

this.security.samlsettings.idp = [{ 
    name: '<IDP name>', 
 
    description: '<Description>', 
    entityID: '<Entity ID obtained from Identity Provider>', 
    ssoURL: '<Single Sign-On URL>', 
    sloURL: '<Logout URL>', 
    ssoBinding: '<post/redirect>', 
    sloBinding: '<post/redirect>', 
    SIGNREQUESTS: true/false, 
    ENCRYPTREQUESTS: true/false, 
    SignCertificate: '<Certificate>' , 
 
    EncryptCertificate: '<Certificate>' 
 
}];

Using File location of IDP metadata

this.security.samlsettings.idp = [ 

    name: '<IDP name>', 
    description:'<Description>', 
    file:'<IDP metadata file location>' 

];

Using URL

this.security.samlsettings.idp = [ 

    name: '<IDP name>', 
    description:'<Description>', 
    url:'<IDP metadata URL>' 

];

Add SP using Application.cfc

this.security.samlsettings.sp = [{ 
    name: '<SP name>', 
    description:'<Description>', 
    entityId: '<Entity ID for SP>', 
    acsURL: '<Assertion Consumer Service URL>', 
    sloURL: '<Logout URL>', 
    ACSBINDING: '<post/redirect>', 
    SLOBINDING: '<post/redirect>', 
    SIGNREQUESTS: true/false, 
    WANTASSERTIONSSIGNED: true/false, 
    LOGOUTRESPONSESIGNED: true/false, 
    SIGNKEYSTOREPATH: '<Path to sign keystore>', 
    SIGNKEYSTOREPASSWORD: '<keystore password>', 
    SIGNKEYSTOREALIAS: '<keystore alias>', 
    requestStore: 'Redis', strict: 'true' 
}];

Azure Blob credentials

application.blobCred = { 
    "vendorName" : "AZURE", 
    "connectionString" : "key" 
}

Azure Blob configuration

application.blobConf = { 
    "serviceName" : "AZURE_BLOB" 
    "options" : { 
        "absorbConditionalErrorsOnRetry" : true/false, 
        "concurrentRequestCount" : 5, 
        "useTransactionalContentMD5" : true/false, 
        "storeBlobContentMD5" : true/false, 
        "disableContentMD5Validation": true/fasle, 
        "singleBlobPutThresholdInBytes" : 12345, 
        "skipEtagLocking" : true/false, 
        "retryPolicyFactory": { 
            "retryPolicyType" : "EXPONENTIAL" | "LINEAR" | "NONE", 
            "deltaBackoffIntervalInMs" : 12, 
            "maxAttempts" : 3, 
            "resolvedMinBackoff" : 1 
        }, 
        "locationMode" : "PRIMARY_ONLY" | "PRIMARY_THEN_SECONDARY" | "SECONDARY_ONLY" | "SECONDARY_THEN_PRIMARY", 
        "maximumExecutionTimeInMs" : 2, 
        "timeoutIntervalInMs" : 1 
    } 
}

Enhancements made in ColdFusion (2018 release) Update 9 and ColdFusion (2016 release) Update 15

Added the followinng flags:

  • this.sessioncookie.samesite = "Strict | Lax | None"
  • this.authcookie.samesite= "Strict | Lax | None"

Application.cfc

component {
                this.name = "MyApp";
                this.sessioncookie.samesite = "Strict";
                this.authcookie.samesite = "Lax";
                this.sessionmanagement = true;
}

Enhancements made in ColdFusion (2018 release) Update 3, ColdFusion (2016 release) Update 10, and ColdFusion 11 Update 18

  • blockedExtForFileUpload to specify a comma-separated list of file extensions for file that must be blocked for uploading.

For example,

{
    this.name="app name";
    this.blockedExtForFileUpload="cfm, cfc, jsp"; //Specify other file extensions
}

The setting blockedExtForFileUpload only applies to the following tags and functions:

  • cffile action="upload"
  • cffile action="uploadall"
  • FileUpload
  • FileUploadAll

You can use "*" (star) to block all files or use "" (empty string) to allow all extensions.

If you are trying to upload a file using the  cffile tag and you want to override the blocked file extensions defined at the server level, specify the extensions. The list overrides the global settings.

For example, you have blocked the extensions,  " cfm , cfc , asp, aspx " in ColdFusion Administrator, but want to upload files of type aspx for your application, use the code below to override the global settings.

component {
        this.name="myApp";
        this.blockedExtForFileUpload="cfm, cfc, asp";
}

Enhancements made in ColdFusion (2018 release)

  • enableNullSupport that specifies if you want to enable support for NULL variables.
  • cache.engine to specify the type of cache engine to be used.
  • Enhancements made in ColdFusion (2016 release)
  • serialization.structmetadata that defines the datatype for a struct key.
  • There is a new application setting, searchImplicitScopes. When set to false, an un-scoped variable is not searched in implicit scopes.
  • passArrayByReference setting, which when set to true, enables you to pass arrays by reference instead of value.

Enhancements made in ColdFusion 11

In ColdFusion 11, you can register application-specific datasources in Application.cfc. These datasources will be specific to that application and will not be available through the Administrator. If there is a name clash with a server-wide datasource, the one specific to the application will be given the priority.

this.datasources.dsn2={
    "driver"="MSSQLServer",
    "username"="sa",
    "password"="password",
    "url"="jdbc:macromedia:sqlserver:
//localhost\MSSQL2008;databaseName=regression;;sendStringParametersAsUnicode=
false;querytimeout=0;MaxPooledStatements=1000"
};

With a custom driver:

this.datasources.dsn3 = { 
    "driver" = "other", 
"url"="jdbc:sqlserver://localhost\MSSQL2008;databaseName=pubs;sendStringParametersAsUnicode=false;querytimeout=0;MaxPooledStatements=1000", 
    "username" = "sa", 
    "password" = "S33N0Ev!l",             
"class"="com.microsoft.sqlserver.jdbc.SQLServerDriver"
};

The following drivers are supported:

  • MSSQLServer
  • Oracle
  • Sybase
  • DB2
  • Informix
  • MySQL_DD
  • PostgreSQL
  • MSAccess
  • Apache Derby Embedded
  • Apache Derby Client
  • MySQL5
  • ODBCSocket
  • Other (for custom driver)

Use this.datasources as shown in the examples below.

// Application.cfc
component {
        this.name = "DSNTest";
        this.datasources = { 
                mssql_app = { 
                    database = "<DBName>", 
                    host = "<HostNameOrIP>", 
                    port = "<portNumber>", 
                    driver = "MSSQLServer", 
                    username = "username", 
                    password = "password" } 
                };
        this.datasource = "mssql_app";
}
<!--- query.cfm --->
<cfscript>
    employees = queryExecute("SELECT * FROM TableName ",[], {datasource="mssql_app"});
    writeOutput(employees);
</cfscript>

Enhancements made in ColdFusion 9.0.1

Application.cfc lets you specify data source authentication details for the data source. The data source settings can now be a string or a struct. When string, it is considered to be the data source name and authentication information is taken from the data source defined in the ColdFusion Administrator.

You can specify the authentication information using a struct value for data source. The following are the key names:

  • name: data source name
  • username: Username for the data source
  • password: Password for the data source

Example

<this.datasource={name='cfartgallery', username="user", password="passwd"}>
or
<this.datasource="cfartgallery">

Note: The same convention is used for ORM default data source where you can specify the data source authentication information in the ormsettings.
The following application-specific attributes have been added for Amazon S3 integration:

  • accessKeyId: ID for Amazon S3 account.
  • awsSecretKey: Secret key for S3 account.
  • defaultLocation:}}The default location of Amazon S3 bucket creation. A bucket on S3 storage can be in one of the following regions: {{US, EU, or US-WEST.The defaultLocation provided in the Application.cfc defines the default location for the bucket that you create. The default value is US.

Example

this.s3.accessKeyId = "key_ID";
this.s3.awsSecretKey = "secret_key";
this.s3.defaultLocation="location";
</cfscript>

Application-specific In-memory file system

You can use in-memory file system specific to applications. This enables application isolation for your virtual file system. That is, the file created in the in-memory file system by one application will not be accessible to another application.

The settings can be specified in the Application.cfc as follows:

Variable

Description

this.inmemoryfilesystem.enabled

Set the value to true to enable in-memory file system for application. This is the default setting.

this.inmemoryfilesystem.size

Specify the memory limit in MB for the in-memory file system.You can also specify the value in the ColdFusion Administrator (Server Settings > Settings > Memory Limit per Application for In-Memory Virtual File System).The lesser value is considered.


Other examples

To come.

No comments:

Post a Comment