Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..
SYS-CON.TV
Today's Top SOA Links


Java for CFers - Part 2 of 3
Java for CFers - Part 2 of 3

As I explained last month (and in several columns earlier this year), Java is here to stay, and Allaire is fully embracing the technology. For ColdFusion developers this is a scary proposition. The thing we love most about CF is that it's easy, simple, and rapid - and those arent adjectives usually used to describe Java.

Or, rather, it was a scary proposition. As I showed you last month, server-side Java can actually be relatively painless. The trick is to use JSP - JavaServer Pages, a scripting-style interface that gives you access to all the benefits of Java without the pain.

As promised, this month we'll continue our look at JSP (using Allaires JRun application server, which I strongly recommend that you download and play with).

Note: Those of you who attended the Allaire Developer Conference last month were fortunate enough to see Java-based CF in action. You also learned that CF5 is not based on Java, and that all initial tests show that Java-based CF (the version after CF5) executes faster than the current C-based CF.

URL Parameters and Form Fields
Continuing last months analysis of comparable CFML and JSP code, let's look at what it would take to access URL parameters or FORM fields. The following is a simple link with two parameters passed to a second page:

<A HREF="page2.cfm?fname=Ben&lname=Forta">Click</A>

In ColdFusion you could display the passed data as simply as this:

<CFOUTPUT>
Hello #fname# #lname#
</CFOUTPUT>

The JSP equivalent is just as simple. Within JSP pages a set of objects are always available to you. Now before you panic, don't let the term object scare you - you don't need to understand object-oriented development to use these objects, as you're about to see. There is a whole range of objects you can use to perform all sorts of operations. For example, the "application" object is used to read and write application-wide data (much like ColdFusion APPLICATION variables), the "session" object is used to work with session variables (much like ColdFusion SESSION variables), and the "response" object is used to send data (for example, cookies) back to the browser (much like using the <CFCOOKIE> tag, for example). One of the most important objects is the "request" object, which is used to retrieve information that is passed from the browser during a request. This is the object youd use to return URL parameters (and form fields too).

The following is the JSP equivalent of the above CFML code:

Hello <%=request.getParameter("fname")%>
<%=request.getParameter("lname")%>

JSP objects have "methods" associated with them - which can be thought of as functions pertaining to an object. Any interaction with an object occurs via the appropriate methods; "request" has a method named getParameter, which is used to retrieve a specified parameters value. request.getParameter("fname"), for example, retrieves the fname parameter.

Of course, if you prefer, you could retrieve the values and save them to variables for later use (as you could do in ColdFusion). Heres a commented example of this:

<%--- Get URL parameters ---%>
<% String fname=request.getParameter("fname"); %>
<% String lname=request.getParameter("lname"); %>
<%--- Display name ---%>
Hello <%=fname%> <%=lname%>

JSP doesn't distinguish between parameter types, so if fname and lname had been FORM fields, the code would have still worked as is. And unlike ColdFusion, JSP wont throw an error if the specified parameter doesn't exist. Instead it'll return an empty string.

As you can see, access user data is only slightly more involved than it is in ColdFusion.

Managing Sessions
ColdFusion programmers use the SESSION scope for any data that needs to persist between requests. Session state management in JSP (and JRun in particular) is very similar to ColdFusion. As already mentioned, the session object is used to manage session data. In JRun, as in ColdFusion, client sessions are automatically created when needed if session state management is enabled. And like ColdFusion, session state management in JRun is turned on per application (although in JRun this is done in the application definition in the administrative tool and not in a tag). And again, as in ColdFusion, cookies are used to send an ID back and forth.

Heres how youd set a SESSION variable in CF:

<CFSET SESSION.name="Ben">

And here's the JSP equivalent:

<% session.setAttribute("name", "Ben") %>

Reading session variables is just as easy. Heres the CFML syntax:

SESSION.name

And here's the JSP equivalent:

session.getAttribute("name");

Simple as that. Oh, and you'll like this one - you don't have to lock variable access in JSP.

Working with Databases
So far, so good. But now it gets a little ugly. As you've seen thus far, JSP provides language elements and objects for all sorts of basic operations. But when you need to interact with external systems (like databases), things arent as simple.

There is no JSP tag or language element for database access. We ColdFusion developers take tags like <CFQUERY> (and <CFMAIL>, <CFPOP>, etc.) for granted sometimes. Developers using other languages often find themselves jumping through hoops to achieve the same functionality. And as database access is such an important part of application development, this warrants special attention.

So, to set the stage, here's some simple CFML code, the kind you and I write every day:

<!--- Retrieve data --->
<CFQUERY DATASOURCE="forta.com" NAME="articles">
SELECT title FROM articles
</CFQUERY>
<!--- Loop through and display results --->
<CFOUTPUT QUERY="articles">
#title#<BR>
</CFQUERY>

Now you're really going to appreciate CFML. As JSP has no special database support, developers have to use lots of embedded Java. The equivalent of the above code (take a deep breath and make sure you're sitting down) could look a lot like this:

<%@ page import="java.sql.*,javax.sql.*,javax.naming.*,java.io.*"%>
<%
// Set DB access code.
String dsName = "Forta.com";
Connection dbConnection = null;
Statement dbStatement = null;
String sqlStatement = "SELECT title FROM articles";
ResultSet dbResultSet = null;

try
{
// Define JNDI InitialContext object.
InitialContext ctx = new InitialContext();
// Look up data source in InitialContext.
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/" + dsName);
dbConnection = ds.getConnection();
// Create Statement object.
dbStatement = dbConnection.createStatement();
// Execute the query.
dbResultSet = dbStatement.executeQuery(sqlStatement);
// Print the result set.
int rows = 0;
//Step through the result set.
while (dbResultSet.next())
{
rows++;
// Display row contents.
thisLine = "";
for (int i = 0; i < colCount; i++)
{
// Column index is based on 1.
thisLine += dbResultSet.get
String(i +1);
thisLine += "<br>";
}
}
}
catch (Exception e)
{
out.println("<p>Exception in main try block");
e.printStackTrace();
}
// Do this no matter what.
finally
{
// Clean up.
try
{
if (dbResultSet != null) {
dbResultSet.close();
}
if (dbStatement != null) {
dbStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
catch (SQLException sqlex)
{
out.println("<p>SQL exception in
finally block");
sqlex.printStackTrace();
}
}
%>

Okay, so calling it a little ugly was a bit of an understatement - truth is, it's downright horrid. In fact, it's not even JSP, it's Java, plain and simple. JSP is a simplified interface to Java, but when the appropriate simplification doesn't exist, JSP developers must resort to using Java. Or must they?

Note: Like ColdFusion developers, JSP developers use database drivers to interact with databases. But instead of ODBC, they use a JDBC driver (similar to JSP, but Java based). ODBC drivers actually can be used with JSP (via a special piece of software called a bridge), but for performance and scalability reasons you won't want to use ODBC drivers this way on a production site.

Once Again, It's All About Tags
The most significant recent enhancement to the JSP spec is support for Tag Libraries - or, as we CFers would call them, Custom Tags. JSP provides a mechanism to encapsulate and black-box underlying code in much the same way as ColdFusion does - using tags and tag families, and by passing attributes to them. Your JSP code will still use Java (like the code above), but you don't have to know or care about it - you just use tags and they do all the work.

Which is great, except that standardized Tag Libraries for the most part don't exist yet - youll have to create your own. Unless, of course, you happen to be using JRun as your JSP server (why on earth would you use any other product anyway?). JRun comes with a set of Tag Libraries, which (and this should come as no surprise) include all sorts of tags that closely mimic the behavior of CFML tags. You can use the sql tag (which is similar to <CFQUERY>) and the foreach tag (which is similar to <CFOUTPUT>) and pass the appropriate attributes to them - the tags do all the heavy lifting.

The following is a block of JSP code (using JRun Tag Libraries) that accomplishes the same thing as the previous Java code:

<%@ page import="allaire.taglib.*,java.sql.*" %>
<%@ taglib uri="jruntags" prefix="jrun"%>
<%--- Execute SQL ---%>
<jrun:sql datasrc="forta.com" id="articles">
SELECT title FROM articles
</jrun:sql>
<%--- Loop through results ---%>
<jrun:foreach item="i" group="<%= articles %>">
<%= i.title %><BR>
</jrun:foreach>

Okay, so it isn't CFML, but it is orders of magnitude better than straight Java. Once again (as we CFers knew year's ago), the future of application development is tags.

Summary
Weve covered a lot of ground by now, and I hope that Java (via JSP) is a lot less scary, and maybe even somewhat intriguing. But there's more, and in the next issue we'll conclude this series with a discussion on using Java and ColdFusion together. Stay tuned.

About Ben Forta
Ben Forta is Adobe's Senior Technical Evangelist. In that capacity he spends a considerable amount of time talking and writing about Adobe products (with an emphasis on ColdFusion and Flex), and providing feedback to help shape the future direction of the products. By the way, if you are not yet a ColdFusion user, you should be. It is an incredible product, and is truly deserving of all the praise it has been receiving. In a prior life he was a ColdFusion customer (he wrote one of the first large high visibility web sites using the product) and was so impressed he ended up working for the company that created it (Allaire). Ben is also the author of books on ColdFusion, SQL, Windows 2000, JSP, WAP, Regular Expressions, and more. Before joining Adobe (well, Allaire actually, and then Macromedia and Allaire merged, and then Adobe bought Macromedia) he helped found a company called Car.com which provides automotive services (buy a car, sell a car, etc) over the Web. Car.com (including Stoneage) is one of the largest automotive web sites out there, was written entirely in ColdFusion, and is now owned by Auto-By-Tel.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

liked it


Your Feedback
sebastian mork wrote: liked it
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE