Welcome!

ColdFusion Authors: Maureen O'Gara, Hovhannes Avoyan, Yakov Fain, Pat Romanski, Liz McMillan

Related Topics: ColdFusion

ColdFusion: Article

Beef Up Your Apps with Enterprise JavaBeans

Beef Up Your Apps with Enterprise JavaBeans

ColdFusion MX has opened up an entirely new world for us CF developers, and along with its new J2EE underpinnings comes an entirely new development construct for us to use in our application development: Enterprise JavaBeans.

EJBs aren't really a bunch of beans, but rather a specification. The EJB specification defines a methodology for deploying robust and distributed components. What this can do for you, in a nutshell, is increase the number of layers in your application. And this is a good thing.

Prerequisites
Before I get started, some words of caution: first, EJB isn't available within the ColdFusion MX standard application server. EJB runs in a separate "container." This container handles a bunch of services for the enterprise beans (these are what the actual components are called), exactly the way that ColdFusion handles a number of services for your Web applications, such as session management and transaction handling. This means that to use EJB you have to have CFMX installed on top of a J2EE server that includes such an EJB container - for example, Macromedia's JRun, Sun's iPlanet, and IBM's WebSphere (check www.macromedia.com for CFMX compatibilities).

Second, EJB isn't necessary for every application. In fact, most applications will be better served by other component methodologies, like JavaBeans (yes, this is confusing, but JavaBeans isn't the same as EJB) or ColdFusion Components (CFCs).

The Old CF Way
Until now, we CF developers have developed our applications using what is called three-tier application development. (A little history: two-tier applications were the old client/server apps - one tier being the thick-client tier, the other the database tier. The Web brought a much better method for accessing applications, but because of HTML/browser limitations, having a thick client was pretty much out of the question. Thus three-tier development was born.)

Three-tier development has, obviously, three tiers: the user interface, the application logic (usually in an application server like ColdFusion), and the data layer (see Figure 1). Three tiers offer a lot of benefits over two tiers. For starters, the client tier displays only the data, saving processing needs on the client machine, as well as allowing for the use of cell phones or PDAs. Also, by breaking up the application and data tiers, both can be clustered or load balanced, allowing applications to scale as more users jump on.

n-Tier Application Development
Enter n-tier development. Yes, this is the same n that brought us next n interfaces and to the "nth" degree. With n-tier development you increase the division of the application even more, from four layers on up. This includes adding services (like the many offered by J2EE or Java Message Service [JMS] and Java Naming and Directory Interface [JNDI]) and components (see Figure 2). The most important aspect of n-tier development is the use of these components to further separate pure business logic from program flow.

In Figure 2 ColdFusion is controlling the application and serves as the interface between the client and the components and datasources. In n-tier development the components (in the form of JavaBean components, COM or CORBA objects, CFCs, or EJB components) handle all of the business logic, leaving .cfm pages (or servlets or JSP pages) to generate the UI, handle requests from clients, and send the appropriate responses.

The n-tier development approach offers several benefits:

  • It's highly modular, allowing for easy updates and component swapping.
  • It's scalable. Each layer can be improved or clustered individually.
  • Clear separation of UI and program logic alone has many benefits:
    -Allows designers and programmers to focus on core competencies
    -Allows you to change underlying code without changing the UI
  • Components can be accessed from external non-CF/Web applications.
This last point is a key component of EJB. Which leads us to the next section: What is EJB and when should it be used?

Defining Enterprise JavaBeans
Here are the facts: EJB is an industry standard. As such, a number of different J2EE application servers provide services for EJB. EJB components can't be developed in any programming language other than Java, though some have similar approaches to the same problem. Enterprise beans can be accessed from any Java application - this includes ColdFusion, JSP, servlets, applets, and even rich Java desktop applications. They can be accessed locally or remotely - a huge point to remember. Most other component methodologies, such as (nonenterprise) JavaBeans, only allow you to access components locally from within the application server. Additionally, you can use ColdFusion (or other services) to deploy your enterprise beans as XML-based Web service components, allowing just about any application to use them, no matter what programming language is used.

You could create an enterprise bean, for example, to handle your shipping calculations. This complex business logic can then be accessed from applications throughout your enterprise: your e-commerce engine, ERP system, and Java-based sales reporting application. If you ever need to change your shipping mechanisms - to take advantage of UPS or FedEx exposing their calculation logic remotely to your company, for example - you only need to change the programming within the enterprise bean. None of the other applications require changes.

Advantages of Using EJB
As you can see, an enterprise bean can be a powerful component, handling many of the transactions and processes that take place within your applications. EJB components offer many benefits - for example:

  • They're deployable, which allows them to be accessed remotely.
  • They're container-managed, saving development time when programming services and offering a number of additional benefits, such as session and persistence management.
  • EJB allows you to cluster your components so you can have multiple servers handling only one component, further breaking up your applications and ensuring availability.
  • EJB 2.0 (the latest EJB specification version) allows for asynchronous and synchronous messaging (see "Message-Driven Beans" section).

    Part of the initial vision behind the EJB specification was to create a "component marketplace" where developers could find plug-and-play functionality for their applications, like a big-boned tag gallery. Truth be told, this marketplace hasn't grown as fast as predicted, but some good components are out there. Take a look at www.componentsource.com/java and http://industry.java.sun.com/solutions.

    Anatomy of an Enterprise Bean
    When you first receive an enterprise bean, either from the Java programmers in your organization or downloaded from a component broker, it's a simple JAR file, as in Java ARchive. You can examine the contents if you like, using WinZip. What you'll find are the following items:

  • Home interfaces: Clients work with the home interface to generate bean objects.

  • Remote interfaces: It's the remote interface that allows any Java application to access the bean, even from across a network.

  • Local interfaces: This allows clients to access the bean locally instead of remotely (the default method for accessing beans), thus saving overhead.

  • Enterprise bean classes: These are the actual "beans" that are created to perform the necessary functions.

  • Deployment descriptor: This is an XML file that tells the EJB container important information about how to handle this specific enterprise bean.

  • Possibly other JAR files or proprietary Java .class files: These will contain programming utilities that are used in the enterprise bean.

    Often Java IDEs or application server providers will provide wizards to ease the creation of these items. For example, Macromedia provides a wizard that creates the interfaces and the deployment descriptor and can even deploy the bean directly to JRun.

    Types of Enterprise Beans
    The different types of beans and what they're used for is a deep and ongoing study, certainly deeper than I can possibly go into here. That said, a brief introduction to session, entity, and message-driven beans is in order.

    Session Beans
    Simply put, session beans provide business logic. The example I stated previously for calculating shipping would be done using a session bean. Session beans are called such because they generally exist for a single "session" as invoked by a client. These beans are stored in memory and the EJB container gets rid of them when the client times out (much like session variables in CF). Session beans have two subtypes: stateful and stateless. The difference is about what you'd expect: a stateful session bean maintains state with the client. You'd use such a bean if you wanted to store information like an e-commerce shopping cart that relates directly to a client and must be maintained until the client is finished.

    Stateless session beans generally perform functions that don't require this. The shipping bean example would probably be stateless; it would be created for the time required to calculate the shipping price and no more. In other words, stateful beans have a memory, stateless beans do not.

    Entity Beans
    Entity beans, unlike session beans, are persistent. Whereas session beans exist for a session, entity beans are permanently stored. In general, each entity bean instance represents a single row from a database. Entity beans are directly mapped to your database, so changes made to the bean will eventually be committed to the database.

    Why, you might ask, wouldn't I just want to work directly with the database? Actually, entity beans handle data extremely well. Because your database information is in memory, you can access the information faster, plus entity beans will (1) manage transactions, (2) allow concurrent access to information, (3) allow for transaction callbacks, and (4) cache data between transactions. Keep in mind that this is enterprise-level middleware - there's nothing exciting here, but as your applications grow you'll need these features more and more. EJB allows you to add these middleware services without having to code them yourself.

    Message-Driven Beans
    The most complicated to understand of all beans is the message-driven bean (MDB), new to EJB 2.0. This is because it requires an understanding of messaging and JMS. Calling on components remotely has some inherent problems: the client must wait while the server is processing, the server must be available (of course), and the component has to deal with a bunch of requests coming in from all directions.

    Messaging is a way to eliminate these burdens. This message-oriented middleware (MOM) sits between the remote application and the local application and acts as a middleman, controlling flow, queuing requests, and returning any results or confirmations as they're processed. JMS is the universal application programming interface for utilizing message services in J2EE. It's through this API that messaging is done in Java.

    MDBs are simply enterprise beans that can respond to requests sent through JMS. These beans don't actually return values or exceptions, but simply act as a mediator between JMS and other components in your n-tier application.

    Example: The following demonstrates the use of an enterprise bean in a CF page. The bean itself (graciously provided by Kristian Cibulskis, one of my coauthors on an upcoming book, Reality ColdFusion: J2EE Integration) is called shippingCalc. Included in this bean is a method, getShippingCost(), that will calculate the shipping cost based on the information passed to it: sender's zip code, recipient's zip code, weight, and shipping method.

    First we must deploy the enterprise bean to the J2EE server. In this example I'm using the full version of JRun 4 Server underneath ColdFusion MX. Because JRun 4 has an autodeployment mechanism built in, I simply copied my class files (and directories) into the CFMX root directory in a folder called /ship-pingCalc. I then added the following entry to the ap-plication.xml file in the <ColdFusion MX root dir>/META-INF/ directory:

    <module>
    <ejb>shippingCalc</ejb>
    </module>

    The bean is now available for use in my CF applications.

    Take a look at the CFML code for testBean.cfm in Listing 1, and follow the steps I took to consume this bean in ColdFusion:

    1.   Create an instance of the Java object javax.naming.InitialContext. This provides the methods to access the catalog of beans available on your J2EE application server. (If you're really interested, this is part of the JNDI API.) This is done using the <CFOBJECT> tag.

    2.   Next, obtain a reference to the bean's home interface. As mentioned earlier, enterprise beans have a number of interfaces. The home interface is used to generate new bean objects. This is done by setting a new variable, home, to the value returned by calling the method initContext.lookup("ShippingCalc"). In Java (and most other object-oriented programming languages), objects generally have a number of methods inherent within them, and are called by listing the object name followed by a dot, then the method name, then parentheses (possibly containing a comma-separated list of arguments, like a CF function). In this example we're calling the lookup() method of the initContext object by passing the String "ShippingCalc", the name of the bean we're looking for.

    3.   Now that you've found the bean, create an actual instance of the bean itself by calling the create() method. Set the bean to the shippingBean variable, which will be the bean reference to access any methods within it.

    4.   For the last step calculate the shipping by calling the getShippingCost() method of the bean (using the shippingBean object you just created) and the necessary arguments. Note the use of the JavaCast() CF function. Java, unlike ColdFusion, has strict datatypes. When passing variables from CF to Java, it's often necessary to "cast" them to the correct datatype to avoid any ambiguity that would otherwise occur in the transition. Here I cast to int and String values.

    That's it! We now have the price to ship a 2.2 pound package from Portland, Oregon, to Minneapolis via Pony Express: $39.92. In your application, of course, you'd most likely want to call this tag using dynamic information (for example, the customer zip code and the total weight of items in the user's shopping cart). But you get the idea. Welcome to the world of J2EE and n-tier application development.

  • Comments (0)

    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.