Beruflich Dokumente
Kultur Dokumente
com
ColdFusion 9
n
n
Basics
n
Working with Data
n
Displaying Data
n
Interacting with Other Technologies
n
Hot Tips and more... By Terry Ryan
more significant to the toolkit than server components in most
About Adobe Coldfusion other competing products.
SharePoint, and Microsoft Office documents specific calls with “cf.” Some developers use CFML to write
their entire application. Others however, use CFML for front
Getting Started end code, display code where CFML mixes well with HTML and
use scripting for their business logic. Most examples of code
Installing ColdFusion in this Refcard will be given in CFML except where showing
You can download a free version of ColdFusion 9 Developer the script version is particularly important, but they all have
from http://adobe.com/go/centaur. Download the appropriate CFscript analogues.
version for your OS, and install. The installer will take you
CFScript
through a few methods of install:
CFScript most closesly resembles JavaScript, but is influenced
Standard by a few different styles of scripting including C, JavaScript and
This installs ColdFusion as a stand-alone server. Despite the ActionScript. Until recently, CFscript was not as fully featured
fact that ColdFusion runs on a J2EE server the stand-alone as CFML. As of ColdFusion 9, one should be able to do
version bundles the J2EE server. This makes the J2EE server anything they can do in CMFL in CFScript.
inaccessible, but the whole package easier to administer for
newcomers to J2EE. This is the easiest way to get started with
ColdFusion.
Multiserver
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.
ColdFusion 9
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.
Parts to Coldfusion
Arguments Variables that are passed in as arguments to a UDF. Values set here accessible
Basics 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
Types methods. It persists across the life of the instance of the CFC. Not thread-safe.
ColdFusion is weakly typed. Variables themselves have no 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
concept of type, but the underlying data does. This means with “local” or by setting with “var” keyword.
that the same variable may act as multiple classical types 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.
without having to be set for them. For example:
<cfset test = 1 /> Custom Tag Scopes
The following scopes are used custom tags.
The variable test can act like a numeric:
Attributes Variables that are passed into a custom tag. Values set here accessible only to
<cfset newTest = test + test />. the currently running call of the custom tag and are therefore thread-safe.
However it can also act like a string in the call: 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
<cfset stringLen = len(test) />. in the custom tag itself.
There are two classes of variables by type in ColdFusion: Variables do not have to be explicitly scoped when referenced,
Simple and Complex. but this is usually preferable for readability and performance.
Simple An unscoped variable call searches the following scope for
Simple variables are variables that are limited to one existence:
unstructured value. They include: String, Numeric, Boolean, or 1) Local �(UDFs and CFCs only) Arguments (UDFs and CFCs only)
DateTime. 2) Variables
Complex 3) CGI
Complex variables are those that either contain structured 4) URL
elements or binary data. They include: structs, arrays, queries, 5) Form
XML, images, and objects. 6) Cookie
7) Client
Scopes
All variables in ColdFusion live in a scope. The scopes are just Session, Application, Server, and Request scopes will not yield
collections of variables that share similar sources or audiences. their values without an explicit reference to them.
They are all ColdFusion struct variables.
Types of ColdFusion Files
Single Request Scopes Page
These scopes only exist for the life of one page. They can only A page is your basic ColdFusion file. �Its file extension is “.cfm.”
be accessed by calls made in that page.
Here is a traditional “Hello World” page.
CGI Contains variables created by the Web server. It gives information like requesting
host, ip address, and complete URI information.
<cfset variable = “Hello World” />
Form These are values passed by a form Post to a page. <cfoutput>#variable#</cfoutput>
Request Prefixing variables with “request” creates this scope. It exists across all calls,
functions, or custom tags, contained within one single request. Custom Tag
URL These are values passed by a form GET to a page or appended as a query A custom tag is a special type of page. It encapsulates
parameter on the tail end of URL request.
commonly used code, and allows you to call it using
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 <cfmodule>, or with the prefix <cf_. �Its file extension is “.cfm.”
call like a custom tag or object call.
Here is a basic custom tag named DisplayDate.cfm:
Persistent Scopes
The following scopes exists for more than the life of one request. <cfparam name=”attributes.date” default=”#now()#”/>
<cfoutput>
They are often the place for storing variables which are used <p>#DateFormat(attributes.date, “mmmm d, yyyy”)#</p>
across the life of a user’s session or an application’s life. </cfoutput>
Application Variables persist across the life of an application. They are accessible by any It takes a date that is passed in and formats it. If no date is
request that has the same application name. passed in it sets the date to Now().
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. You would call it like this:
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 <cf_displayDate >
to a date that is specified when set. <cf_displayDate date =”#CreateDate(2009,7,8)#”>
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 It would display like this:
ColdFusion, like version, OS, etc.
Session Variables persist across the life of a user’s session in a particular application.
July 15, 2009
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. July 8, 2009
not exactly the same as a Java Class. Its file extension is “.cfm.” Postegres. However ColdFusion can interact with any RDBMS
with a JDBC driver.
As of ColdFusion 9, properties yield implicit getters and setters.
Datasources
They can be defined either in CFML:
In order to work with a particular database in ColdFusion, you
<cfcomponent> must first create a datasource. A datasource is the collection
<cfproperty name=”firstName” /> of settings you use to communicate with a database, such as
<cfproperty name=”lastName” />
<cfproperty name=”email”/> database type, sever, port, tablespace, or database, username
<cffunction name=”getDisplayName” returntype=”string”>
<cfreturn This.getFirstName() & “ “ & This.getLastName() />
and password. You collect all of these settings and give them
</cffunction> a meaningful name. ColdFusion then allows you to refer to
</cfcomponent>
just the datasource name when connecting to the database.
Or in CFScript: The server will handle maintaining connections, closing them,
persisting them. In short ColdFusion abstracts database
component{
property firstName;
connections into datasources.
property lastName;
property email; Queries
string function getDisplayName(){
return This.getFirstName() & “ “ & This.getLastName();
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
Either version of the CFC would be called like this: tags allow you to pass a query attribute in for easy iteration.
Within one of those iterators you can just refer to the column
<cfset person = New cfcScriptExample() /> you are calling:
<cfset person.setfirstName(‘Terry’) />
<cfset person.setlastName(‘Ryan’) />
<cfset person.setEmail(‘terry@terrenceryan.com’) /> <cfloop query=”personRS”>
<cfoutput> <cfset fullname = lastName & “, “ & firstName />
<p>#person.getDisplayName()#</p> </cfloop>
<p>#person.getEmail()#</p>
</cfoutput>
Alternately you can choose to manually loop through the query
And they would display this: (broken up for readability):
onRequest Replaces a request. If you use this method, you have to explicitly Additionally ColdFusion allows you to do parameterized
include the intended page or cfc. Useful for wrapping layout and
formatting features around an application.
queries using the cfqueryparam tag.
onRequestEnd Triggered by the end of a request. <cfquery name=”resultSet” datasource=”cfartgallery”>
onRequestStart Triggered by the start of a request. SELECT *
FROM artists
onSessionEnd Triggered the first time a particular user calls a URL in the WHERE artistid =
application. Useful for setting session scoped variables. <cfqueryparam cfsqltype=”cf_sql_integer” value=”1” />
</cfquery>
onSessionStart Triggered when user session ends, usually because the session
timed out.
Stored Procedure
Stored procedures can also be called from ColdFusion using
working with data the <cfstoredproc> tag.
This.datasource The name of the datasource to use for ORM CFCs. <cfset displayName = FirstName & “ “ & LastName />
Relationships
CFCs support Hibernate relationships, and allow you to setup
one-to-one, one-to-many, many-to-one, and many-to-many
relationships.
Mappings
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.
UI Components
Also ColdFusion allows for making queries against the object In addition to being able to output variables to HTML
model using HQL, Hibernate’s SQL-like query language. templates, ColdFusion has built in a number of UI controls for
handling of complex data.
Displaying Data
Interacting with other technologies
Output
The <cfoutput> tag handles basic output of variables. ColdFusion can communicate with a large number of servers,
<cfset variable = “Hello World” /> products and languages using built-in tags.
<cfoutput>#variable#</cfoutput>
Common Services
Pound Signs Mail Servers <cfmail>,<cfimap>, <cfpop>
You might notice the use of pounds signs. Pound signs
Web Servers <cfhttp> (support SSL)
are used to display or pass the literal value of a variable or
FTP Servers <cfftp> (support FTPS and SFTP)
operation. So normally when you set a variable to another
Directory Servers <cfldap>,<cfntauthenticate>
variable, you just pass the variable:
Services
Assume a Web service that provides nuggets of data with a <cfhttp> supports the HTTP verbs that usually get used with
method browse that takes a parameter named age. The idea is REST: get, put, post, delete.
to give me the content that is age days old. It has a wsdl URL
of http://forta.com/cf/tips/syndicate.cfc?wsdl. Here’s how I Formats
would use it: ColdFusion can parse the various formats that come back from
Web services:
<cfset wsURL=”http://forta.com/cf/tips/syndicate.cfc?wsdl” />
<cfinvoke webservice=”#wsURL#” XML <cfxml>, XmlParse()
method=”browse”
returnvariable=”result”> JSON DeserializeJSON()
<cfinvokeargument name=”age” value=”0” />
</cfinvoke> RSS/Atom cfxml>, <cffeed>, XmlParse()
<cfdump var=”#result#”>
Providing
This yields figure 3. SOAP
Any CFC can be turned into a SOAP Web service by adding
access=”remote” to a method:
<cfcomponent>
<cffunction name=”now” access=”remote” returntype=”date”>
<cfreturn Now() />
</cffunction>
</cfcomponent>
REST
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:
http://localhost/ws.cfc?method=now
REST
REST Web services can be consumed by using <cfhttp>. However this might not strike some people as RESTful enough.
Instead you should write an intermediate page between the plain Just the output, assuming it is a simple variable type.
CFC and the caller that uses the HTTP verb to determine the JSON Serializes the results as JSON
method to take. This can be done either by introspecting the RSS/Atom Serializes the results as WDDX
CGI scope or using the GetHTTPHeaders() function.
AJAX AMF
While not a protocol per se, ColdFusion has a tag that allows Finally, any remotely exposed service is also available as a
remote methods to be called from JavaScript. <cfajaxproxy> Flash Remoting or AMF service. This means that it can be
create a JavaScript proxy for a specified CFC and call methods consumed in Adobe Flex using the RemoteObject interface.
on it from JavaScript as a JavaScript object. Using the Web
Adobe ColdFusion Site http://adobe.com/go/coldfusion
service created in the preceding SOAP we can call it and pass
(Download and Licensing Information)
the value to alert:
ColdFusion Developer Center http://adobe.com/devnet/coldfusion/
<cfajaxproxy cfc=”ws” jsclassname=”ws” /> (Articles and Tutorials)
<script type=”text/javascript”>
ColdFusion Bloggers Aggregator http://coldfusionbloggers.org/
wsInstance = new ws();
alert(wsInstance.now()); (ColdFusion Community)
</script>
RIAForge http://riaforge.com
Format (Open Source ColdFusion Projects)
The returnformat of any remote method can be configured to ColdFusion on Twitter http://twitter.com/coldfusion
A B O U T t h e A ut h o r R E C O M M E N D E D Boo k
Terry Ryan is currently an Adobe Platform Evangelist for This Getting Started volume starts with Web and Internet
ColdFusion. His job is to drum up support and excitement fundamentals and database concepts and design, and
among developers for Adobe ColdFusion. He has been then progresses to topics including creating data-driven
working with it for over 10 years. He’s presented at various pages, building complete applications, implementing
Adobe ColdFusion events including cf.Objective, webDU, security mechanisms, integrating with e-mail, building
and Adobe Max. Prior to joining Adobe, Terry worked for the reusable functions and components, generating data-
Wharton School of Business at the University of Pennsylvania driven reports and graphs, building Ajax-powered user
in various roles around ColdFusion from Application Developer to System interfaces, and much more.
Administrator.
BUY NOW
Terrence Ryan | Adobe Platform Evangelist | http://terrenceryan.com books.dzone.com/books/adobe-coldfusion-8-web
Bro
ugh
t to
you
by...
Professional Cheat Sheets You Can Trust
tt erns “Exactly what busy developers need:
n Pa
ld
ona
sig son
McD
simple, short, and to the point.”
De
Ja
By
#8
ired
Insp e
by th
GoF ller con
tinu
ed
ndle
r doe
sn’t
have
to
in tab
Cha d ultip ecific o should cep pat
this if the m up the
man
n M
an ac
z.co
n
sp s ents
be a ject ime. d is see passed
Download Now
Com reter of ob at runt handle plem ks to de to
...
n
uest som tion proces e no m
Itera tor ore req
n A g in metho
d
cep
dm ndlin
e e ar
tho e to ptio th
Exce ion is sm to ha up th tered or
e ca
n
Ob
se Me S renc ral
Refcardz.com
plate RN refe listed in mp
le ce pt ni
echa n pa ssed co un avio
Beh
TTE
n
ex
is en
ick
BIRT Windows Powershell
am
Tem Exa he .
A s has ack. W tion uest to ject
NP a qu s, a ct- cep Ob
it
n
st q
IG e s e rn b je call e ex e re
vid patt able O le th nd th
DES
! V is
pro s, hand s to ha
UT ard ign us ram .
des diag
JSF 2.0 Dependency Injection with EJB 3
ct
ABO refc oF) f Re le obje
erns ts o lass exa
mp oke
r
Patt ur (G lemen es c Inv
arz
n F o d rl d h
Des
ig go
f s: E inclu al w
o suc
Th is G a n
l 23 sign Pa
tt e rn e rn
patt , and a
re je ts
t ob mentin
c g AN
D
Adobe AIR Netbeans IDE JavaEditor
c
a h c M M
ef
in c u
orig kD
e
re.
Ea tion ons
tr ple CO ma
nd
boo Softwa rma to c their im om
BPM&BPMN Getting Started with Eclipse
re R
( low
e x p o n la rg cute is al ch
ati an b rm ts. +exe . Th
bject nship
s su
Cre y c fo je c an o
t th
e
ed
to ob ms, d as ed rela
tio
Get
nsh
ips
that
can psu
Enca quest
the
re
late
sa
and
e ha
to b llbacks
ca
.
nalit
y.
riant
times
or in
varia
ling
the
invo
catio
ing
n.
DZone, Inc. ISBN-13: 978-1-934238-87-5
ra o pose uing nctio led at va hand
io n ti ct cess be
av ,a la P ur
as q
ue
ack
fu je pro
Beh nships t re
1251 NW Maynard
ob
e
ISBN-10: 1-934238-87-2
nd the to
je c a n b callb b e ha eded. m ro nous nality ed
tio ob at c
ed
You ne s need
to ne
sts is couple
d fro
ynch nctio y ne
rela with s th st que
n
e th
e as the fu
itho
ut an is
eals
it
ship Reque y of re de ar
ld be litat pattern ssing w tation articul
e: D tion faci
50795
or
e. Use
n
A hist shou d ce en p
ed to mman for pro implem ents its ting.
cop runtim rela type
ker
Cary, NC 27513
n
S s Whe invo y us
n
s co al m pec
jec t at cla Pro
to Th e
w id el th e ue ue
ac tu
d im
p le ex
are utilizing a job q of the ue is
Ob ged with
n
C ues ueue e que
han eals me.
y dge enq
que s. B en to th
e c : D P roxy Job orithm be giv knowle that is terface
b e ti
cop
g n ct
pile r S in
rato er mp
le of al ed ca to have d obje of the
ss S at com serv
888.678.0399
Exa ut
Deco nes
an
.com
919.678.0300
one
Abst tory
C C
Fac
B
State
t
pte
r eigh y
teg
Ada Flyw Stra od
z
Meth
more than 3.3 million software developers, architects and decision
S S r B
w. d
e rp rete plate
ridg
Refcardz Feedback Welcome
B B
Inte Tem
S B
er tor or
ww
C B r B
NSIB
ILIT
Y B
S
Com
po si te
P O succ
ess
or Sponsorship Opportunities 9 781934 238875
RES
“DZone is a developer’s dream,” says PC Magazine.
F
CH
AIN
O
ace
>> sales@dzone.com
terf r
<<in andle
H st ( )
ndle
Camden, Charlie Arehart, Adobe Press, September 2007 +ha
ern
r 1 king m
dle by lin .c o an uest one
teH req z
cre () le a w.d
Con uest hand | ww