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
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis 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. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote 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. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani 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. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata 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. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...