ColdFusion runs on underlying Java technology, and so support for Java is native to ColdFusion. ColdFusion allows access to Java objects, APIs, EJBs, and more, and also provides special support for JSP Tag Libraries. Using Java ObjectsJava objects, API, beans, and EJBs, are all accessed via the <cfobject> tag. In this example the ColdFusion internal Java factory object is used to obtain a list of defined datasources: <!--- Get "factory" ---> <cfobject action="CREATE" type="JAVA" name="factory"> <!--- Get datasource service ---> <cfset dsService=factory.getDataSourceService()> <!--- Get data sources ---> <cfset dsFull=dsService.getDatasources()> <!--- Extract names into an array ---> <cfset dsNames=StructKeyArray(dsFull)> <!--- List names ---> <ul> <cfloop index="i" from="1" TO="#ArrayLen(dsNames)#"> <cfoutput> <li>#dsNames[i]#</li> </cfoutput> </cfloop> </ul> The function equivalent to <cfobject>, CreateObject(), can also be used to invoke Java objects. Using JSP Tag LibrariesJSP (Java Server Pages) features the ability to create reusable tags (similar to Custom Tags in ColdFusion. JSP Tag Libraries are accessible from within CFML code by importing the Tag Libraries using <cfimport>, as seen here: <!--- Load JSP tag library ---> <cfimport taglib="/WEB-INF/lib/davisor2d.jar" prefix="2d"> <!--- Create image ---> <2d:imageSubmit bgPaint="image-images/#image#" text="#text#" textAlign="#align#" paint="#textcolor#" vpadding="#padding#" hpadding="#padding#" fontface="#fontface#" font="#fontsize#" scope="session" /> This example imports a graphics Tag Library and invokes a method named imageSubmit, which builds an image based on passed text, colors, font information, and more. <cfimport> takes the Tag Library to load as the taglib value, and loads the Tag Library into a namespace specified by prefix. The namespace is then used to invoke specific methods, as in 2d:imageSubmit, which invokes the imageSubmit method in the 2d namespace. Casting VariablesColdFusion is a typeless language, and Java is hard-typed. Therefore, you might need to cast ColdFusion's string variable into a hard-typed Java variable. One reason for this would be for calling an overloaded method because its arguments can take more than one data type. To cast a ColdFusion variable into a Java variable, you use the JavaCast() function, which takes two arguments:
This function should be used only for scalar and string arguments. You use this function inside the <cfobject> tag before you call the Java method to which you want to pass the value. If the method takes more than one overloaded argument, then you must call JavaCast() for each overloaded argument. You cannot use JavaCast() to cast between complex objects or to cast to a superclass. You should use the result of this function only on calls to Java objects. Because there is no one-to-one correspondence between internally stored ColdFusion types and Java scalar types, some conversions cannot be performed. |