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
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, 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. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
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 Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, 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. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...
SYS-CON Events announced today that CHEETAH Training & Innovation 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. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
SYS-CON Events announced today that Datanami has been named “Media 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. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...