Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

A Cold Cup o' Joe Part2

A Cold Cup o' Joe Part2

One of the most important lessons to be learned with any Internet technology is to play nicely with others. In the ever-expanding horizons of ColdFusion this means Java and in the scope of this article, servlets.

There are times when ColdFusion and servlets seem to overlap, and people have a tendency to see them as competing product technologies. There are, however, numerous areas where they can act in a complementary fashion, seeming less like warring camps and more like cooperative agents.

Servlets can provide access to the wide array of Java libraries, which can be used to enhance or extend ColdFusion's capacities with such things as string manipulation, XML manipulation, networking, compression, encryption, graph generation, image creation and manipulation, and PDF creation or formatting. On the Web, both the Allaire Developers' Exchange and Sun Microsystems' servlet resource page (http://java.sun.com/products/servlet/resources.html) provide numerous useful and free servlets.

What You Need to Make It Work
The beauty of using servlets with ColdFusion is that it requires few or no special configurations on the part of the ColdFusion server or the servlet server.

To compile the Java code you'll need a JDK, which can be obtained from Sun Microsystems' JavaSoft Web site (http://java.sun.com/j2ee/ j2sdkee/), as discussed in Part 1 of this series (CFDJ, Volume 3, issue 1). In addition, you'll need the Servlet SDK (a complete version can be downloaded from the JavaSoft Web site, www.javasoft.com/products/servlet/index.html), or you can use JAR files that accompany either Allaire's JRun or the Apache Group's Tomcat products. It's important for the purposes of this article that the servlet library is the 2.2 specification or later. While it's possible to do almost all of the examples in this article on a prior version, the JRun integration is more demanding.

The server you're using - Allaire's JRun or the Apache Group's Tomcat - will determine the default location to install the servlet examples from this article. For JRun, where the base installation directory is <JRUN>, it's <JRUN>\servlets or <JRUN>\servers\default\default-app\WEB-INF\ classes. For Tomcat, where the base installation directory is <TOMCAT>, it's <TOMCAT>\ webapps\ROOT\WEB-INF\classes.

Connecting ColdFusion Server and JRun
While JRun hosts its own Web server and allows for direct connects on a configured port, it also allows for connections through other Web servers, which act as proxies for servlet requests. This intermediary technique allows JRun to better cooperate with other servers. Configuring for interaction between the ColdFusion Server and JRun to enable the use of the <CFSERVLET> tag requires a little tinkering.

It takes four quick steps to configure the external Web server connector, and you're up and running. This process begins by launching the Connection Wizard from the toolbar of the JRun Management Console.

The first step in configuring an external Web server connector is the selection of "Server." This panel prompts for the selection of a JRun Server and an external Web Server (see Figure 1). The JRun Admin Server and JRun Default Server are your stock options for JRun Server, and it's strongly advised that you configure for the Default Server. The Web server options are Apache, Netscape (Enterprise or FastTrack), Microsoft (IIS or PWS), O'Reilly WebSite Pro, or JRun's own Zeus. I'm connecting the JRun Default Server to IIS 5.0 on Windows and Apache 1.3.x on RedHat.

At this point the Connector Wizard prompts you to shut down your Web server before proceeding.

The second step presents a panel for the selection of the address and port number on which the configured JRun Server listens (see Figure 2). I'm configuring for address 127.0.0.1 on port 88.

The content in the third step is dependent upon the Web server selected in the first step. This panel prompts for the installation location and the type of connector plug-in (for example, Figure 3 for IIS on my Windows installation, and Figure 4 for Apache on my Linux installation).

The final panel is merely a success or failure notice along with a summary of the selected configurations (see Figure 5).

A high-level view of this configuration is available in its own panel (see Figure 6). You can access it by unfolding the Default Server parent node in the navigation tree and selecting the "External Web Server" node. From this panel we can administer all the settings we entered in the Connector Wizard. Return to this panel if you need to change the listening port.

To inspect the settings of JRun's Default Server you can access it by unfolding the Default Server parent node in the navigation tree and selecting the "JRun Web Server" node (see Figure 7). From here we can look up the port number the Web server is listening on. For the purposes of this article, mine is set to 8100.

The Quick and Dirty of a Java Servlet
A Java servlet is a compiled Java class that inherits from the javax.servlet.http.HttpServlet class. The kinds of requests the servlet is to handle (e.g., HTTP GET and POST) will determine which methods the HttpServlet subclass overrides, doGet or doPost. These methods receive two parameters, a request object and a response object. Passed arguments can be drawn from the request object, and an output stream object can be created from the response object.

The code in Listing 1 (Code Listings 1-6 appear on the CFDJ Web site) shows a servlet written to respond to both GET and POST methods and will output a simple "Hello, World" string. It takes an optional parameter, Name. I've overridden both doGet and doPost to forward to the same class method, since the different means of calling servlets from ColdFusion require flexible routing, as we'll see later.

Connecting to a Servlet
There are a number of ways HTML and CFML can incorporate servlets. Any tag that can connect to a URL is a viable option. The HTML tags for anchors, form actions, and the implementation-specific <SERVLET> tag, and even image sources and the CFML tags <CFLOCATION>, <CFFORM>, <CFHTTP>, and <CFSERVLET> present us with a number of possibilities. The two that we'll discuss are <CFHTTP> and <CFSERVLET>. These tags allow a controlled two-way communication between CFML code and the servlet.

Serving It Up
I'll discuss how to make your ColdFusion application integrate generically with servlet engines, then focus on the specific benefits of using <CFSERVLET> and the JRun server. While the techniques discussed for use with <CFHTTP can be applied to any servlet engine, use of <CFSERVLET> can only be done with JRun.

Where possible, I've tested with both JRun 3.0 SP1 and Apache's Tomcat 3.2 extension under both Windows 2000 Professional and RedHat Linux 6.2. (The details of the configurations are covered in the first article of this series.)

The dizzying array of port numbers passed about in this article can create conflict. In all cases my Web server listens on the default port (80). The rest of my configurations are as follows:

  • JRun Default Server on port 8100
  • JRun External Connector on port 88
  • Tomcat Connector on port 8080
This collection of port numbers allows me to run all but my default Web server at once.

Web Server to Web Server
The <CFHTTP> tag is powerful in that it's Web-technology agnostic. Through <CFHTTP> we can connect to a servlet without the need (or conversely, the benefit) of the advanced hooks that Allaire provides with JRun and the <CFSERVLET> tag.

Calling a servlet with <CFHTTP> requires a minimum of three attributes: URL, Port, and Method. As might be inferred, the URL attribute specifies the URL to the servlet itself; Port is the port the target server is listening on for the servlet request; and Method is the HTTP GET or POST method.

To call the servlet from Listing 1 without a parameter using JRun:

<CFHTTP URL="http://localhost/servlet/Listing1" Port="8100" Method="GET">

And with Tomcat:

<CFHTTP URL="http://localhost/servlet/Listing1" Port="8080" Method="GET">

We can programmatically access the resulting string from the CFML variable, CFHTTP.FileContent.

Passing values to the servlet is equally easy and requires the use of the tag <CFHTTPPARAM>. This subordinate tag requires three attributes: Name, Value, and Type. The Name attribute specifies the name of the servlet parameter being passed; the Value is the value of the servlet parameter; and Type is the mode that the parameter will be passed. Available modes are: URL, FormField, Cookie, File, and CGI.

Here's an example of this with JRun:

<CFHTTP URL="http://localhost/servlet/Listing1" Port="8100" Method="POST">
<CFHTTPPARAM Name="name" Value="Guy" Type="FormField">
</CFHTTP>

And with Tomcat:

<CFHTTP URL="http://localhost/servlet/Listing1" Port="8080" Method="POST">
<CFHTTPPARAM Name="name" Value="Guy" Type="FormField">
</CFHTTP>

Notice that the Method attribute of <CFHTTP> changed to POST. Usage stipulates that in order to call <CFHTTPPARAM> the Method must be POST. This also means that the servlet's doPost class method will get invoked.

Leveraging JRun
With <CFSERVLET>, a template can not only call a servlet but also get values returned directly into variables. This powerful feature alone allows you to create robust applications. To call a servlet with <CF-SERVLET> requires a minimum of four attributes: Code, JRunProxy, Timeout, and WriteOutput. The Code attribute specifies the name of the servlet CLASS file (or its configured alias); the JRunProxy attribute specifies the address and port where the JRun external connector server is listening; Timeout is the number of seconds to wait before reporting a failure; and WriteOutput is a Yes/No value that specifies whether the servlet's output is entered directly into the stream back to the Web server (the default value is Yes). If WriteOutput is set to No, then the servlet output can be retrieved from the CFSERVLET.Output variable.

All servlets called with <CF-SERVLET> are called with the HTTP GET method, meaning that its doGet class method will be invoked.

An example of this is:

<CFSERVLET Code="Listing1" JRunProxy="127.0.0.1:88" Timeout="300" WriteOutput="Yes">
</CFSERVLET>

Passing parameters to a servlet requires the subordinate tag <CF- SERVLETPARAM>, which has a minimum of two attributes: Name and Value. The Name attribute is the name of the passed parameter and Value is its value.

<CFSERVLET Code="Listing1" JRunProxy="127.0.0.1:88" Timeout="300" WriteOutput="Yes">
<CFSERVLETPARAM Name="name" Value="Guy">
</CFSERVLET>

Unlike <CFHTTPPARAM> values, <CFSERVLETPARAM> can be linked to CFML variables, and values can be received as well as sent. This is an important factor in constructing robust applications and nearly as simple as the snippet in Listing 1. The <CFSERVLETPARAM> needs an additional attribute with which to specify the output location. The Variable attribute must identify an existing variable to receive the returning value. Attribute combinations of Name, Value, and Variable are illegal, so you must specify the ingoing value with one <CFSERVLETPARAM> statement and specify the outgoing variable with another.

On the last line of the doGet class method the servlet in Listing 2 shows a call to the setAttribute method of the incoming Request object. This call sets up the return of a value through the JRun server to the calling template.

<CFSET str="In">
<CFSERVLET Code="Listing2" JRunProxy="127.0.0.1:88" Timeout="300" WriteOutput="Yes">
<CFSERVLETPARAM Name="str" Value="in">
<CFSERVLETPARAM Name="str" Variable="str">
</CFSERVLET>
<CFOUTPUT>#str#</CFOUTPUT>

The <CFSERVLETPARAM> tag also has another important attribute: Type. By default ColdFusion passes strings into a servlet; the Type attribute allows for the preservation of specific data types. The Type at-tribute can be INT, DOUBLE, BOOL, DATE, or STRING.

Here's an example of sending in a Boolean value:

<CFSET str="In">
<CFSET flag="false">
<CFSERVLET Code="Listing3" JRunProxy="127.0.0.1:88" Timeout="300" WriteOutput="Yes">
<CFSERVLETPARAM Name="str" Value="in">
<CFSERVLETPARAM Name="str" Variable="str">
<CFSERVLETPARAM Name="flag" Variable="flag" Type="BOOL">
</CFSERVLET>
<CFOUTPUT>#str#</CFOUTPUT>

Toggling the value of the "flag" variable between "True" and "False" determines whether there's a modification made to the returning "str" variable. Examining the servlet in Listing 3, you can see that just after displaying the incoming parameter "str", the "flag" attribute is retrieved. After some conversion between the Java Boolean object and Boolean primitive, the code evaluates the True/False condition and determines whether to set the outgoing value.

Another example of passing typed variables can be found in the JRun documentation, Developing Applications with JRun, Chapter 42, "Using JRun with ColdFusion."

Wrapping It Up
It's possible to leverage existing servlet resources or even whole applications without too much difficulty. Further, if the servlet server is JRun, it only takes a little tinkering to have strong interaction between ColdFusion templates and servlets. Leveraging existing servlets (many of which are free) can push your ColdFusion application over the edge, with toolkits for generating PDF documents, graphs, images, and more.

Compiled in Listing 4 are all the CFML snippets from this article. Listing 5 is a more complex servlet designed for tracing calls through a servlet and its life cycle, similar to the SnoopServlet that comes with both JRun and Tomcat. You can use this for further study of how servlets work, specifically their interaction with other Web technologies. Listing 6 is a simple modification of Listing 3 to call the tracing servlet from Listing 5.

In testing the code for this article I ran into an interesting problem. I originally created a WAR that was to be made available from the CFDJ Web site. Unfortunately this didn't work very well with the <CFSERVLET> examples. After hunting through documentation and scouring the forums it appears that deployed WARs aren't easily accessible with <CFSERVLET>. According to a post by Bob Love at Allaire's JRun Forum (http://forums.allaire.com/JRunconf/Index.cfm?Message_ID=578270), the only WAR that JRun recognizes for <CF-SERVLET> is the default application. This is one of the two default locations that <CFSERVLET> will look for servlets to execute. This fact was only recently reiterated in the <CF-SERVLET> documentation found in ColdFusion Studio 4.5.2 (which was released at the time this article was written).

After talking with sales engineers from Allaire I found that it's possible to amend the CLASSPATH setting of JRun's Default Server to include the servlet subdirectory of a deployed WAR. This allows servlets from various WARs to be found by <CF-SERVLET>. I didn't find this to be an acceptable solution, however, since the global settings of the application aren't inherited in this way.

More Stories By Guy Rish

Guy Rish is a ColdFusion and .NET developer at Vente as well as President at Gestaltech. He is an active developer and writer for various languages and technologies, and has contributed work in books on ColdFusion MX, Flash MX, and Dreamweaver MX. He blogs at ccoj.coldfusionjournal.com.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Jr 09/24/03 10:08:36 PM EDT

I'm writing a CFMX/Java app. I have cf connecting to the java class file, however when I output the info, it's output the java resultset instead of the row I'm requesting...any suggestions?

@ThingsExpo Stories
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...