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 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">

And with Tomcat:

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

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="" Timeout="300" WriteOutput="Yes">

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="" Timeout="300" WriteOutput="Yes">
<CFSERVLETPARAM Name="name" Value="Guy">

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="" Timeout="300" WriteOutput="Yes">
<CFSERVLETPARAM Name="str" Value="in">
<CFSERVLETPARAM Name="str" Variable="str">

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="" Timeout="300" WriteOutput="Yes">
<CFSERVLETPARAM Name="str" Value="in">
<CFSERVLETPARAM Name="str" Variable="str">
<CFSERVLETPARAM Name="flag" Variable="flag" Type="BOOL">

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
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO 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 over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
The IoT Will Grow: In what might be the most obvious prediction of the decade, the IoT will continue to expand next year, with more and more devices coming online every single day. What isn’t so obvious about this prediction: where that growth will occur. The retail, healthcare, and industrial/supply chain industries will likely see the greatest growth. Forrester Research has predicted the IoT will become “the backbone” of customer value as it continues to grow. It is no surprise that retail is ...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
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...