Over a million developers have joined DZone.
Refcard #066

Getting Started With ColdFusion 9

A Rapid Application Development Toolkit

by Terrence Ryan

Great start sheet that lists various ways of communicating with databases, other tools, services and languages.

Free PDF
Getting Started With ColdFusion 9
Section 1

About Adobe Coldfusion

Adobe ColdFusion is a rapid application development toolkit that is written in Java and runs on top of the JVM. Its core philosophies are: make things easy, and provide RAD without restricting developers.

This Refcard will take you through getting started with ColdFusion 9. It will take you through the various pieces and languages that comprise ColdFusion. It will also list various ways of communicating with databases, other tools, services, and languages. This Refcard is aimed at programmers in other languages that are considering taking a look at ColdFusion.

ColdFusion 9

ColdFusion 9 is currently in public beta and scheduled to be released before then end of 2009. It is a significant release in that it includes substantial additions to the feature set, including: Hibernate, Ehcache, full language support for scripting, interactivity with Java portal servers, Microsoft SharePoint, and Microsoft Office documents

Section 2

Getting Started

Installing ColdFusion

You can download a free version of ColdFusion 9 Developer from http://adobe.com/go/centaur. Download the appropriate version for your OS, and install. The installer will take you through a few methods of install:


This installs ColdFusion as a stand-alone server. Despite the fact that ColdFusion runs on a J2EE server the stand-alone version bundles the J2EE server. This makes the J2EE server inaccessible, but the whole package easier to administer for newcomers to J2EE. This is the easiest way to get started with ColdFusion.


This will install ColdFusion as a single instance running on JRun. This will allow you to install multiple ColdFusion servers on your box if you wish. Additionally, JRun is a J2EE server capable of running other EAR or WAR files.

EAR/WAR file

This will package ColdFusion and your installation options into a J2EE EAR or WAR file. This file can then be deployed to the

J2EE server of your choice.

Section 3

Parts to Coldfusion

ColdFusion consists of two parts: the server that runs ColdFusion, and the code you run on it. The server is a little more significant to the toolkit than server components in most other competing products


The server component of ColdFusion consists of an executable server that can run as a service or daemon on your OS. This server component handles processing ColdFusion requests but also stores a lot of configuration for your applications centrally. This allows you to configure your datasources in one place, and then just refer to them by alias in your code. You can also set things like mail server defaults, central code collections, path mappings, third party licenses, etc. Most of what you can set here can be overridden at the application level, but by setting it here, you can avoid having to store that information in your applications.


ColdFusion uses two languages for writing code:


CFML is a tag-based language that prefixes all ColdFusion specific calls with “cf.” Some developers use CFML to write their entire application. Others however, use CFML for front end code, display code where CFML mixes well with HTML and use scripting for their business logic. Most examples of code in this Refcard will be given in CFML except where showing the script version is particularly important, but they all have CFscript analogues.


CFScript most closesly resembles JavaScript, but is influenced by a few different styles of scripting including C, JavaScript and ActionScript. Until recently, CFscript was not as fully featured as CFML. As of ColdFusion 9, one should be able to do anything they can do in CMFL in CFScript.

Section 4



ColdFusion is weakly typed. Variables themselves have no concept of type, but the underlying data does. This means that the same variable may act as multiple classical types without having to be set for them. For example:

<cfset test = 1 />

The variable test can act like a numeric:

<cfset newTest = test + test />.

However it can also act like a string in the call:

<cfset stringLen = len(test) />.

There are two classes of variables by type in ColdFusion: Simple and Complex.


Simple variables are variables that are limited to one unstructured value. They include: String, Numeric, Boolean, or DateTime.


Complex variables are those that either contain structured elements or binary data. They include: structs, arrays, queries, XML, images, and objects.


All variables in ColdFusion live in a scope. The scopes are just collections of variables that share similar sources or audiences. They are all ColdFusion struct variables.

Single Request Scopes

These scopes only exist for the life of one page. They can only be accessed by calls made in that page.

CGI Contains variables created by the Web server. It gives information like requesting host, ip address, and complete URI information.
Form These are values passed by a form Post to a page.
Request Prefixing variables with “request” creates this scope. It exists across all calls, functions, or custom tags, contained within one single request.
URL These are values passed by a form GET to a page or appended as a query parameter on the tail end of URL request.
Variables This is the default scope for variables in a request that are not in another scope. It is only accessible within the main flow of the request, and not directly in any other call like a custom tag or object call.

Persistent Scopes

The following scopes exists for more than the life of one request. They are often the place for storing variables which are used across the life of a user’s session or an application’s life.

Application Variables persist across the life of an application. They are accessible by any request that has the same application name.
Client Variables persist across the life of a user’s session in a particular application. They are accessible from any call for a particular user in a particular application. Unlike every other scope, its values can be stored on disk or database.
Cookie Variables persist either across the life of the user’s browser session, or according to a date that is specified when set.
Server Variables persist across the life of the server. They are accessible by any call anywhere on the server. Also contains information about the server instance of ColdFusion, like version, OS, etc.
Session Variables persist across the life of a user’s session in a particular application. They are accessible from any call for a particular user in a particular application. Unlike the Client scope, the values are stored in server memory.

Component and UDF Scopes

The following scopes are used with CFCs and user defined functions (UDFs.)

Arguments Variables that are passed in as arguments to a UDF. Values set here accessible only to the currently running call of the UDF and are therefore thread-safe.
This In CFC the variables scope is accessible externally and to any of the internal methods. It persists across the life of the instance of the CFC. Not thread-safe.
Local Private scope for a UDF. Values set here accessible only to the currently running call of the UDF and are therefore thread-safe. Created by prefixing variables with “local” or by setting with “var” keyword.
Variables In CFC the variables scope is accessible internally to the any of the methods and persists across the life of the instance of the CFC. Not thread-safe.

Custom Tag Scopes

The following scopes are used custom tags.

Attributes Variables that are passed into a custom tag. Values set here accessible only to the currently running call of the custom tag and are therefore thread-safe.
Caller An alias for the variables scope of the calling page of a custom tag.
Variables The default scope for variables in a custom tag. Values here are only accessible in the custom tag itself.

Variables do not have to be explicitly scoped when referenced, but this is usually preferable for readability and performance. An unscoped variable call searches the following scope for existence:

Local (UDFs and CFCs only) Arguments (UDFs and CFCs only)

  1. Variables
  2. CGI
  3. URL
  4. Form
  5. Cookie
  6. Client

Session, Application, Server, and Request scopes will not yield their values without an explicit reference to them.

Types of ColdFusion Files


A page is your basic ColdFusion file. Its file extension is “.cfm.”

Here is a traditional “Hello World” page.

<cfset variable = “Hello World” />

Custom Tag

A custom tag is a special type of page. It encapsulates
commonly used code, and allows you to call it using
<cfmodule>, or with the prefix <cf_. Its file extension is “.cfm.”

Here is a basic custom tag named DisplayDate.cfm:

<cfparam name=”attributes.date” default=”#now()#”/>
<p>#DateFormat(attributes.date, “mmmm d, yyyy”)#</p>

It takes a date that is passed in and formats it. If no date is passed in it sets the date to Now().

You would call it like this:

<cf_displayDate >
<cf_displayDate date =”#CreateDate(2009,7,8)#”>

It would display like this:

July 15, 2009

July 8, 2009


A ColdFusion Component, or CFC for short, is a collection of properties and UDFs wrapped together. It is analogous to but not exactly the same as a Java Class. Its file extension is “.cfm.”

As of ColdFusion 9, properties yield implicit getters and setters.

They can be defined either in CFML:

<cfproperty name=”firstName” />
<cfproperty name=”lastName” />
<cfproperty name=”email”/>
<cffunction name=”getDisplayName” returntype=”string”>
<cfreturn This.getFirstName() & “ “ & This.getLastName() />

Or in CFScript:

property firstName;
property lastName;
property email;
string function getDisplayName(){
return This.getFirstName() & “ “ & This.getLastName();

Either version of the CFC would be called like this:

<cfset person = New cfcScriptExample() />
<cfset person.setfirstName(‘Terry’) />
<cfset person.setlastName(‘Ryan’) />
<cfset person.setEmail(‘terry@terrenceryan.com’) />

And they would display this:

Terry Ryan


Application Framework

ColdFusion code is packaged into Applications. Applications are comprised of folders, files, and an Application.cfc. The Application.cfc stores settings that allow a developer to handle the behavior of applications, sessions and requests. There are a number of methods that ColdFusion can respond to in this file:

onApplicationEnd Is not triggered when the application times outs or the server shuts down gracefully.
onApplicationStart Is triggered the first time an application is called. You can use this function to initialize application variables.
onError Is triggered whenever an uncaught exception is raised anywhere in the application.
onMissingTemplate Triggered whenever a request is made for a cfm or cfc that doesn’t exist in the application. Can be used to simulate virtual files.
onRequest Replaces a request. If you use this method, you have to explicitly include the intended page or cfc. Useful for wrapping layout and formatting features around an application.
onRequestEnd Triggered by the end of a request.
onRequestStart Triggered by the start of a request.
onSessionEnd Triggered the first time a particular user calls a URL in the application. Useful for setting session scoped variables.
onSessionStart Triggered when user session ends, usually because the session timed out.
Section 5

Working with Data

ColdFusion was originally designed to be a language to bridge backend databases to Web pages. As such, handing record sets from database is a key part to using ColdFusion.


ColdFusion has built in support for many flavors of database including: Microsoft SQL, MySQL, Oracle, Derby, DB, and Postegres. However ColdFusion can interact with any RDBMS with a JDBC driver.


In order to work with a particular database in ColdFusion, you must first create a datasource. A datasource is the collection of settings you use to communicate with a database, such as database type, sever, port, tablespace, or database, username and password. You collect all of these settings and give them a meaningful name. ColdFusion then allows you to refer to just the datasource name when connecting to the database. The server will handle maintaining connections, closing them, persisting them. In short ColdFusion abstracts database connections into datasources.


A recordset returned from a database will be turned into
a special type of variables called, in ColdFusion, a query
variable. <cfloop> and <cfoutput> along with a number of other
tags allow you to pass a query attribute in for easy iteration.
Within one of those iterators you can just refer to the column
you are calling:

<cfloop query=”personRS”>
<cfset fullname = lastName & “, “ & firstName />

Alternately you can choose to manually loop through the query (broken up for readability):

<cfloop index=”i” from=”1” to=”# personRS.recordCount#”>
<cfset fullname = personRS .lastName[i] />
<cfset fullname = fullname & “, ” />
<cfset fullname = fullname & personRS .firstName[i] />

In order to help looping and paging, queries have a few special properties.

ColumnList A comma delimited list of columns in the query.
CurrentRow The current row that is being accessed in the context of a cfoutput or cfloop call.
RecordCount The total number of records


Calling SQL is a matter of using <cfquery> with a datasource:

<cfquery name=”resultSet” datasource=”cfartgallery”>
SELECT * FROM artists

Additionally ColdFusion allows you to do parameterized queries using the cfqueryparam tag.

<cfquery name=”resultSet” datasource=”cfartgallery”>
FROM artists
WHERE artistid =
<cfqueryparam cfsqltype=”cf_sql_integer” value=”1” />

Stored Procedure

Stored procedures can also be called from ColdFusion using the <cfstoredproc> tag.


As of ColdFusion 9, Hibernate is baked into ColdFusion and allows CFCs to be mapped to database tables.

Enabling ORM

To enable ORM for an application, the following settings are required in the Application.cfc:

This.datasource The name of the datasource to use for ORM CFCs.
This.ormenabled A Boolean which turns on ORM.


Assuming that a table named “person” with columns firstName, lastName, and email exists, and that there is a primary key personID, here is the code for a CFC named person.cfc that is mapped to the table:

<cfcomponent persistent=”true”>
<cfproperty name=”personID” fieldtype=”id” />
<cfproperty name=”firstName” />
<cfproperty name=”lastName” />
<cfproperty name=”email”/>

Data from the table can then be retrieved using the EntityLoad() function:

<cfset resultSet = entityLoad(“artists”) />

Or one record (with id = 5) can be requested:

<cfset resultSet = entityLoad(“artists”, 5) />

Creating a new record uses the EntityNew() function:

<cfset person = entityNew(“artists”) />

Then whether you are creating or updating a record, the code is the same:

<cfset person.setFirstName(“Terry”) />
<cfset person.setLastName(“Ryan”) />
<cfset person.setEmail(“terry@terrenceryan.com”) />
<cfset EntitySave(person) />

Deleting records would use the EntityDelete() Function:

<cfset EntityDelete(person) />


CFCs support Hibernate relationships, and allow you to setup one-to-one, one-to-many, many-to-one, and many-to-many relationships.


CFCs also support more advanced features of Hibernate including: Join Mapping, Collection Mapping, Inheritance Mapping, and Embedded Mapping.

Hibernate Options

In additional to all of the features that ColdFusion enables through CFCs, it also can take hbm.xml files to model your objects.

Also ColdFusion allows for making queries against the object model using HQL, Hibernate’s SQL-like query language.

Section 6

Displaying Data


The <cfoutput> tag handles basic output of variables.

<cfset variable = “Hello World” />

Pound Signs

You might notice the use of pounds signs. Pound signs are used to display or pass the literal value of a variable or operation. So normally when you set a variable to another variable, you just pass the variable:

<cfset displayName = FirstName & “ “ & LastName />

You can also pass the literal value:

<cfset displayName = “#FirstName# #LastName#” />

Dumping Data

One of the most helpful debugging tags in ColdFusion is <cfdump>. It will just output the value of the variable. For simple variables, this looks exactly like <cfoutput>, but for complex variables, <cfdump> will format a representation of the data to make it easy to understand. Take for example a call to a page:


Those query parameters get passed to the URL scope as discussed Scopes. You can dump the URL scope because it is a struct:

<cfdump var=”#url#”/>

It yields figure 1.

figure 1

If we were to dump a query:

<cfquery name=”rs” datasource=”cfartgallery” maxrows=”5” >
SELECT firstName, lastName, City, State
FROM artists
<cfdump var=”#rs#”>

It yields figure 2.

figure 2

UI Components

In addition to being able to output variables to HTML templates, ColdFusion has built in a number of UI controls for handling of complex data.

Section 7

Interacting with Other Technologies

ColdFusion can communicate with a large number of servers, products and languages using built-in tags.

Common Services

Mail Servers <cfmail>,<cfimap>, <cfpop>
Web Servers <cfhttp> (support SSL)
FTP Servers <cfftp> (support FTPS and SFTP)
Directory Servers <cfldap>,<cfntauthenticate>

Microsoft Servers


<cfexchangeconnection>, <cfexchangecalender>,
<cfexchangeccontact>, <cfexchangefilter>,
<cfexchangetask>, <cfexchangemail>

SharePoint <cfsharepoint>


PDF <cfdocument>, <cfpdf>
Office Documents <cfdocument>, <cfspreadsheet>, <cfpresentation>


Using the tag <cfobject> or the function CreateObject() you can create completely accessible objects for the Java, or .Net. For example you can pass info from .Net to Java in two lines of code:

<cfset pwd = CreateObject(“.Net”, “System.IO.Directory”).
getCurrentDirectory() />
<cfset jStr = CreateObject(“java”, “java.lang.String”).init(pwd)

In addition, the object tools allow you to interface COM and CORBA.

Section 8


A large part of current Web development is programming to and against service APIs. ColdFusion has a number of built in tools to consume and produce services using either SOAP or REST.



ColdFusion is able to consume SOAP Web services, by using either the <cfinvoke> or <cfobject> tags. You simply point them at the WDSL of the service.

Assume a Web service that provides nuggets of data with a method browse that takes a parameter named age. The idea is to give me the content that is age days old. It has a wsdl URL ofhttp://forta.com/cf/tips/syndicate.cfc?wsdl. Here’s how I would use it:

<cfset wsURL=”http://forta.com/cf/tips/syndicate.cfc?wsdl” />
<cfinvoke webservice=”#wsURL#”
<cfinvokeargument name=”age” value=”0” />
<cfdump var=”#result#”>

This yields figure 3.

figure 3


REST Web services can be consumed by using <cfhttp>.

<cfset restURL = “http://search.twitter.com/search.json” />
<cfset searchTerm = “ColdFusion” />
<cfhttp url=”#restURL#?q=#searchTerm#” result=”response” />

The result will be a ColdFusion struct with a number of keys. The json response will be the key fileContent. It will be in the json format and will have to be parsed into a ColdFusion XML variable:

<cfset serverResponse = “#deserializeJSON(response.fileContent)#”
<cfdump var=”#serverResponse#”>

This yields figure 4.

figure 4

<cfhttp> supports the HTTP verbs that usually get used with
REST: get, put, post, delete.


ColdFusion can parse the various formats that come back from Web services:

XML <cfxml>, XmlParse()
JSON DeserializeJSON()
RSS/Atom cfxml>, <cffeed>, XmlParse()



Any CFC can be turned into a SOAP Web service by adding access=”remote” to a method:

<cffunction name=”now” access=”remote” returntype=”date”>
<cfreturn Now() />

ColdFusion will autogenerate the wsdl for you if you append “?wsdl” to the URL of the CFC:http://localhost/ws.cfc?wsdl


CFCs with remote methods can also be called as REST service. To call the Web service created in the preceding SOAP section you just append the method to the URL:


However this might not strike some people as RESTful enough. Instead you should write an intermediate page between the CFC and the caller that uses the HTTP verb to determine the method to take. This can be done either by introspecting the CGI scope or using the GetHTTPHeaders() function.


While not a protocol per se, ColdFusion has a tag that allows remote methods to be called from JavaScript. <cfajaxproxy> create a JavaScript proxy for a specified CFC and call methods on it from JavaScript as a JavaScript object. Using the Web service created in the preceding SOAP we can call it and pass the value to alert:

<cfajaxproxy cfc=”ws” jsclassname=”ws” />
<script type=”text/javascript”>
wsInstance = new ws();


The returnformat of any remote method can be configured to a couple of options:

plain Just the output, assuming it is a simple variable type.
JSON Serializes the results as JSON
RSS/Atom Serializes the results as WDDX


Finally, any remotely exposed service is also available as a Flash Remoting or AMF service. This means that it can be consumed in Adobe Flex using the RemoteObject interface.

Adobe ColdFusion Site (Download and Licensing Information) http://adobe.com/go/coldfusion
ColdFusion Developer Center (Articles and Tutorials) http://adobe.com/devnet/coldfusion/
ColdFusion Bloggers Aggregator (ColdFusion Community) http://coldfusionbloggers.org/
RIAForge (Open Source ColdFusion Projects) http://riaforge.com
ColdFusion on Twitter (Announcements) http://twitter.com/coldfusion

Recommended Book

Coldfusion book


This Getting Started volume starts with Web and Internet fundamentals and database concepts and design, and then progresses to topics including creating data-driven pages, building complete applications, implementing security mechanisms, integrating with e-mail, building reusable functions and components, generating datadriven reports and graphs, building Ajax-powered user interfaces, and much more.


  • Featured
  • Latest
  • Popular
Getting Started With Docker
Teaches you typical Docker workflows, building images, creating Dockerfiles, and includes helpful commands to easily automate infrastructure and contain your distributed application.
10.2k 7,169
Getting Started With Real User Monitoring
Teaches you how to use new web standards—like W3C’s Beacon API—to see how your site is performing for actual users, letting you better understand how to improve overall user experience.
4,442 3,655
Core Java
Gives you an overview of key aspects of the Java language and references on the core library, commonly used tools, and new Java 8 features.
104k 263.9k
JavaFX 8
Gives you what you need to start using the powerful JavaFX 8 UI and graphics tool with code snippets and visual examples of shapes and controls.
6,786 8,934
Continuous Delivery With Jenkins Workflow
Provides an introduction to the Jenkins Workflow plugin, a tool that extends the popular CD application to manage even the most complex software pipelines and help you continuously deliver more efficiently.
8,663 9,673
Functional Programming in JavaScript
Explains functions, data types, and techniques to demonstrate the functional paradigm through the familiar JavaScript language.
12k 8,665
Java Caching
Explores the building blocks of JCache and other caching APIs, as well as multiple strategies for implementing temporary data storage in your application.
10.5k 10.5k
Getting Started With Microservices
Still re-deploying your entire application for one small update? Microservices deploy modular updates and increase the speed of application deployments.
13.7k 14.1k
Getting Started With MQTT
Explores the fundamentals of MQTT, including message types, QoS levels, and security.
6,068 7,092
Monitoring NGINX
Overcome dropped connections, server errors, and more by efficiently monitoring your NGINX web server.
4,874 3,800
Getting Started With Apache Tomcat
Learn Apache Tomcat, a pure Java open-source web server that implements the Java Servlet, JavaServer Pages, and Expression Language specifications.
8,845 7,314
IntelliJ IDEA Essentials
Helps Java developers navigate the various facets of this world-class IDE, with tips, tricks, shortcuts, and quick tutorials on editor basics, navigation, and more.
20.4k 91k
{{ card.title }}
{{card.downloads | formatCount }} {{card.views | formatCount }}

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}