BUY THIS BOOK
Add to Cart

Print Book $34.95


Add to Cart

Print+PDF $45.44

Add to Cart

PDF $27.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint or License this content?


JBoss at Work: A Practical Guide
JBoss at Work: A Practical Guide By Tom Marrs, Scott Davis
October 2005
Pages: 306

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Getting Started with JBoss
Have you noticed that simply saying "I am a Java programmer" isn't enough these days? It conveys a little bit of information, but not enough to make any serious decisions. It's kind of like saying, "I play sports" or "I like food." A recruiter can assume that a Java programmer has a passing familiarity with curly braces and semicolons, but little else.
The Java programming language runs on an incredibly diverse set of hardware—from cell phones and PDAs down to embedded chips on a credit card; every major desktop and laptop, regardless of operating system or hardware manufacturer; entry-level workgroup servers up to clusters of high-end servers; and even mainframes.
The mantra in the heady early days of Java was, "Write once, run anywhere." The original ideal of having the same application run anywhere from a cell phone to a large-scale cluster of servers turned out to be more marketing hype than business reality, although the "run anywhere" part of the slogan has proven remarkably prescient.
Modern Java developers often define themselves by the hardware they specialize in. J2ME developers eke amazing functionality out of resource-starved micro-devices with limited networking capabilities. J2SE programmers have mastered daunting but robust GUI frameworks such as Swing and SWT for rich desktop application development. And J2EE software engineers are masters of the server-side domain.
Saying that you are a J2EE programmer begins to narrow the field a bit, but our hypothetical recruiter still doesn't have enough information to place you in the proper job. J2EE is a loose collection of server-side technologies that are related, but are by no means homogenous.
Some J2EE experts specialize in web-related technologies—JSPs, Servlets, and the diverse landscape of web frameworks such as Jakarta Struts or Sun's Java Server Faces. Others are back-end specialists that focus more on the transactional integrity and reliability of business processing that uses technologies such as EJBs, JMS, and relational databases. (We'll define these acronyms later in the book.) There is even a new breed of Web Services specialists that use the J2EE product suite and a host of related XML technologies, such as SOAP and WSDL, to offer a Service Oriented Architecture to Java and non-Java clients alike.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why "JBoss at Work"?
Before we get too far into things, we should explain why we chose the title JBoss at Work for this book. Understanding the authors' backgrounds should help.
Both of us are practicing software engineers who have worked together off and on for years. More importantly, both of us are former presidents of the Denver Java Users Group (http://www.denverjug.org). When we polled the group for potential interest in a given subject, the same phrase came up over and over again: "I don't want to be an expert in it, I just want to make it work."
"I just want to make it work" really resonates with us because we feel the same way. An ever-growing number of technologies fall under the J2EE umbrella, and there are at least two or three competing implementations of each. Just trying to keep up is a never-ending battle.
There is a 1,000-page book out there for each topic we cover in only 20 to 30 pages. JBoss At Work isn't intended to be an exhaustive discussion of every facet of the J2EE collection. This book is meant to be a brief survey of each subject aimed at the working professional with limited time—"Give me an overview, show me some working code, and make it snappy...." (Think of it as 12 months of JUG presentations collected in a single volume, minus the PowerPoint slides and cold pizza.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why JBoss?
JBoss fits the "I just want to make it work" gestalt to a T. Depending on the speed of your Internet connection, you can have it downloaded, unzipped, and running in less than five minutes. Turning services on and off is as simple as adding or removing files from a directory. The fact that it's free means that you don't get bogged down with per-seat or per-CPU licensing costs. JBoss is both a great learning tool and a production-quality deployment environment.
But any tool as powerful as JBoss also has pitfalls and complexities. The biggest disservice we could do is show you how to write applications that are tied to a specific application server, JBoss or otherwise. The "Write Once, Run Anywhere" promise of J2EE development may not happen automatically, but you can take steps to minimize the impact of moving from one application server to the next. In addition to your code being more portable, being a non-partisan J2EE developer means that you and your skills are more portable as you move from one job to the next.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Example: JAW Motors
We have tried to come up with an application that uses each layer of the J2EE collection in some sort of meaningful way. By design, this book is short on academic discussions and long on working code examples. Showing a coherent business application in action will hopefully give you a clearer idea of how the various layers interact, as opposed to a series of disjointed "Hello World" examples exercising each layer in isolation.
The JAW Motors application supports a fictitious automobile dealership. Each chapter progressively adds a new J2EE technology that solves a specific business problem. Viewing cars on a website involves JSP pages and some form of persistence (JDBC or Hibernate). Performing a credit check sends a JMS message and an email response using JavaMail. Purchasing a car requires the transactional support of Stateless Session Beans. Sharing data from the JAW Motors inventory with other dealerships involves setting up Web Services.
In addition to showing how JBoss works, we hope that these examples answer the how and why of each technology: how is it used, and why it should (or shouldn't) be used. Just because a hammer can sink a screw in drywall doesn't necessarily mean that it is the best tool for the job. The measure of a successful J2EE application isn't how many of the technologies it uses; it is how effectively each technology is used.
Source code for the JAW Motors application is available for download from http://www.jbossatwork.com. We encourage you to download the files and build them as you follow along in the book. We want you to literally see JBoss at work, not just read about it.
Before we get too far, let's make sure that you have all necessary tools to build and deploy the application to JBoss.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Tools
Making JBoss work involves more than just downloading and running JBoss. A cook certainly needs to know how to run the oven, but a lot of preliminary work must happen before the dish is ready for baking.
Professional chefs call this set up process "mis en place." They sharpen knives and place cutting boards within arms' reach. They prepare ahead of time ingredients they can safely cut up and measure before the dinner rush. Everything that can be done in terms of efficiency is handled up front so the culinary artist isn't distracted by mundane details.
Similarly, making JBoss work effectively requires you to do a bunch of work up front. Code must be compiled and packaged up in a specific way. You must wade through endless deployment descriptors. If one tiny piece of information doesn't match up with its companion in another file, the application will not deploy properly, and all of your hard work will be for nothing.
The mis en place of JBoss development involves other tools that make it easy to handle the mundane details of building and deploying your application. As in JBoss, you can download and use all of these tools for free:
  • Java
  • Ant
  • XDoclet
Let's talk briefly about how to install and configure them.
It probably goes without saying that the first thing you'll need is a working installation of Java. JBoss 4.0.2 is compatible with J2SE 1.4 or higher. We use J2SE 1.4.2 in this book, although nothing should prevent you from running the examples in Java 5.
Download the full JDK (Java 2 Development Kit) from Sun's web site (http://java.sun.com). Follow Sun's instructions for installing the JDK on your operating system. Next, create an environment variable called JAVA_HOME that points to the Java installation directory. Finally, add $JAVA_HOME/bin to the system path so you can run Java from the command line.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing JBoss
Now that we have all prerequisites in place, we can get to the reason why you are here: installing and running JBoss.
Download the JBoss Application Server Version 4.0.2 from http://www.jboss.org. Since it is written in Java, the same installation files will work on Windows, Linux, Unix, or Mac OS X. Any platform that has a JVM can run JBoss.
To install JBoss, simply unzip the downloaded file to the directory of your choice. Next, create an environment variable called JBOSS_HOME that points to the JBoss installation directory. Finally, add $JBOSS_HOME/bin to the system path so you can run JBoss from the command line.
To verify your JBoss installation, type run at a command prompt (run.bat for Windows users, run.sh for Linux/Unix/Mac users). You should see something like this in your terminal window:
    rosencrantz:/Library/jboss/bin sdavis$ ./run.sh
    ===========================================
    ==============================

      JBoss Bootstrap Environment

      JBOSS_HOME: /Library/jboss

      JAVA: /System/Library/Frameworks/JavaVM.framework/home/bin/java

      JAVA_OPTS: -server -Xms128m -Xmx128m -Dprogram.name=run.sh

      CLASSPATH: /Library/jboss/bin/run.jar:/System/Library/Frameworks/
      JavaVM.framework/home/lib/tools.jar

    ===========================================
    ==============================

    22:14:03,159 INFO  [Server] Starting JBoss (MX MicroKernel)...
    22:14:03,177 INFO  [Server] Release ID: JBoss [Zion] 4.0.2
    (build: CVSTag=JBoss_4_0_2 date=200505022023)
    22:14:03,181 INFO  [Server] Home Dir: /Library/jboss-4.0.2

    [many lines deleted for clarity...]

    22:14:55,890 INFO  [Http11Protocol] Starting Coyote
    HTTP/1.1 on http-0.0.0.0-8080
    22:14:56,396 INFO  [ChannelSocket] JK: ajp13 listening on /0.0.0.0:8009
    22:14:56,519 INFO  [JkMain] Jk running ID=0 time=0/240  config=null
    22:14:56,530 INFO  [Server] JBoss (MX MicroKernel)
     [4.0.2 (build: CVSTag=JBoss_4_0_2 date=200505022023)]
    Started in 53s:238ms
If you don't see any exceptions scroll by, JBoss is up and running when you see the final line:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying Applications to JBoss
J2EE applications are generally bundled up as Enterprise Archives (EARs) or Web Archives (WARs). JBoss services can be bundled up as Service Archives (SARs). While each application technically is nothing more than a simple Java Archive (JAR), they have special internal directory structures and configuration files that must be present for the sake of the application server. (We will discuss EARs and WARs in greater detail later in the book.)
Knowing when to use these different file types and where to place them can be confusing. Here are some basic principles:
  • $JBOSS_HOME/lib is for the application server's dependent libraries. These file types should always be packaged as JARs. You should never put your own JARs in this directory.
  • $JBOSS_HOME/server/[server configuration]/lib is for the Server Configuration's dependent libraries. These, too, should always be JARs. You may add an occasional database driver JAR to this directory.
  • $JBOSS_HOME/server/[server configuration]/deploy is for SARs, WARs, and EARs. Plain old JARs will be ignored if placed here directly, although all three types of files may themselves contain JARs.
If you haven't done so already, go to http://www.jbossatwork.com and download the code examples. Once you've unzipped the downloaded file, copy jaw.war from the ch01/ 01a-test directory to $JBOSS_HOME/server/default/deploy. In the JBoss console window, you should see the deployed test application.
To verify that the application was deployed correctly, open a web browser and go to http://localhost:8080/jaw (see Figure 1-2).
Figure 1-2: JAW Motors web page
Note that our WAR is treated no differently than an MBean. If you move jaw.war
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Looking Ahead...
Now that you've had a chance to see JBoss at work, let's begin writing our web application. The next chapter walks you through the basics of building and deploying a WAR.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Web Applications
In this chapter, we'll begin writing the JAW Motors application. First, we'll explain some basic architectural principles like the MVC pattern of web development. Then we'll explore the building blocks of the web tier (JSP, JSTL, CSS, and servlets). Finally, we'll use ANT to create WAR files and deploy them to JBoss.
Our goal is not to teach you these technologies and techniques from scratch—they should be familiar to most web developers already. This chapter is meant to be a quick overview and demonstration of the technology working in JBoss. For deeper look into web tier software and development best practices, look at Head First Servlets & JSP, by Bryan Basham, Kathy Sierra, and Bert Bates (O'Reilly).
The servlet container is the core J2EE technology that powers the web tier. It is considered a container because JSPs and servlets cannot run as standalone applications—they must implement special interfaces and run "inside" the container. The container listens for HTTP requests on a given port, hands the incoming data to your custom components, and uses the resulting output to create a well-formed HTML document to return to the web browser as the response.
The JBoss developers wisely chose not to create their own servlet container to meet this need. A number of excellent ones already are out there. Rather than recreating the wheel, JBoss allows you to integrate the servlet container of your choice.
Tomcat 5.5.9 is the default servlet container included with JBoss 4.0.2. It is deployed as a SAR in $JBOSS_HOME/server/default/deploy/jbossweb-tomcat55.sar.
If you are comfortable working with Tomcat, you should have no trouble working in JBoss. All the usual configuration files and JARs are in the Tomcat directory. For example, edit server.xml to change the port Tomcat listens on. (8080 is the default.) To change the default session timeout from 30 minutes, edit conf/web.xml. (For more information about installing and configuring Tomcat, see Tomcat: The Definitive Guide by Jason Brittain and Ian F. Darwin (O'Reilly).)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Servlet Container
The servlet container is the core J2EE technology that powers the web tier. It is considered a container because JSPs and servlets cannot run as standalone applications—they must implement special interfaces and run "inside" the container. The container listens for HTTP requests on a given port, hands the incoming data to your custom components, and uses the resulting output to create a well-formed HTML document to return to the web browser as the response.
The JBoss developers wisely chose not to create their own servlet container to meet this need. A number of excellent ones already are out there. Rather than recreating the wheel, JBoss allows you to integrate the servlet container of your choice.
Tomcat 5.5.9 is the default servlet container included with JBoss 4.0.2. It is deployed as a SAR in $JBOSS_HOME/server/default/deploy/jbossweb-tomcat55.sar.
If you are comfortable working with Tomcat, you should have no trouble working in JBoss. All the usual configuration files and JARs are in the Tomcat directory. For example, edit server.xml to change the port Tomcat listens on. (8080 is the default.) To change the default session timeout from 30 minutes, edit conf/web.xml. (For more information about installing and configuring Tomcat, see Tomcat: The Definitive Guide by Jason Brittain and Ian F. Darwin (O'Reilly).)
Thanks to the modular design of JBoss, swapping out Tomcat for another servlet container is easy. Jetty is another option that is fast, mature, and open source. (As a matter of fact, it was the default container included with JBoss 3.x.) Go to http://jetty.mortbay.org/jetty/download.html to download a pre-built SAR, ready to drop in and run.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Three-Tier Applications
Before we dive into writing our code, let's take a moment to talk about some architectural principles. This discussion will set the stage for this chapter and the rest of the book.
The parts of a J2EE application fall into three basic tiers:
  • The presentation tier is the collection of J2EE components that comprise the UI. For web applications, this tier includes components like Servlets and JSPs.
  • The business tier is so named because it is where your business logic lives. The technologies that live here include EJBs and MDBs.
  • The persistence tier is where your data is stored for the long term. It generally involves a relational database, but isn't limited to that. You could store your data as XML, serialized JavaBeans, or even plain old ASCII text files.
In a well-engineered application, components in each tier are "highly cohesive" and "loosely coupled". By highly cohesive, we mean that each component should do only one thing. By loosely coupled, we mean that components across the tiers shouldn't depend on one another unnecessarily.
For example, a getCars() method call should return only data. The data shouldn't be preformatted into HTML. If it is, your data tier knows too much about the presentation tier. The two tiers are highly coupled.
An unfortunate side effect of this coupling is that deciding to add a new presentation technology later (like a Swing client) will force you to rewrite a portion of your persistence tier as well. If instead your persistence tier returns data and lets the presentation tier concern itself with the formatting, then you can reuse your persistence tier across multiple UIs. Loosely coupled tiers encourage reuse.
You also could argue that the persistence tier fails the highly cohesive test. It is concerned with too many things—data and presentation. A clean separation of concerns is what we are hoping to accomplish.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exploring the Presentation Tier
So, here we are at the presentation tier . The same principles of high cohesiveness and loose coupling are as applicable within this tier as they are across tiers. In the presentation tier, it is known as the Model / View / Controller (MVC) pattern.
  • The view is the actual screen. It is implemented using JSPs, CSS, and taglibs like the JSTL. It is concerned only about formatting the data in a pleasing way.
  • The model is the data. In a "View Cars" screen, the model is a Plain Old Java Object (POJO). In our case, it is a simple JavaBean named CarBean .
  • The controller mediates communication between the View and the Model. If a "viewCarList" request comes in, it retrieves the CarBeans from the persistence layer and hands them to the view. In a web application, the controller generally is a servlet.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building the View Cars Page
Let's begin by implementing the View Cars page. As you can imagine, the first thing most people do when they visit a car dealership is walk around the lot to see which cars the dealer has in stock. In a similar vein, we'll create a view that allows visitors to "walk the lot" via the web.
This view also gives us an excuse to explore the structure of a WAR file. We'll deploy the WAR to JBoss and see it run in container. Once we have that much under our belt, we'll swing back around and do a quick refactoring to implement the model and controller.
JSPs are plain HTML files with some templating capabilities that enable us to plug in data dynamically at runtime. Here is an example of our page using static HTML. (We'll add the dynamic content in just a moment.) Example 2-1 should give you a basic feel for what the webpage will look like, and Figure 2-1 shows the result in a web browser.
Example 2-1. carList.html
<html>
<body>
  <table border="1">
    <tr>
      <th bgcolor="cccccc" align="left">Make</th>
      <th bgcolor="cccccc" align="left">Model</th>
      <th bgcolor="cccccc" align="right">Model Year</th>
    </tr>

    <tr>
      <td align="left">Toyota</td>
      <td align="left">Camry</td>
      <td align="right">2005</td>
    </tr>


    <tr>
      <td align="left">Toyota</td>
      <td align="left">Corolla</td>
      <td align="right">1999</td>
    </tr>


    <tr>
      <td align="left">Ford</td>
      <td align="left">Explorer</td>
      <td align="right">2005</td>
    </tr>
  </table>
</body>
</html>
Figure 2-1: carList.html rendered in a web browser
Now that we see what we are working toward, let's make this page dynamic. To start, we'll fill the data table using pluggable values rather than using static HTML.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding a Model and Controller
Now we have a working skeleton. Let's add the model and controller to complete the MVC framework.
The model is a Plain Old Java Object (POJO). You've built classes like this a thousand times before. CarBean is nothing more than a class with three member variables and the associated accessors and mutators.
As you saw in the previous JSP example, using string arrays for data storage doesn't yield very expressive source code. We use an object-oriented programming language to build objects that have a deeper semantic meaning than a pile of primitive data types. In Example 2-9, you can see that CarBean is nothing more than a class with three member variables and the associated accessors and mutators. Car.make, Car.model, and Car.modelYear mean something to us, as opposed to the use of string [0], string [1], and string [2].
Example 2-9. CarBean.java
package com.jbossatwork;

public class CarBean
{
    private String make;
    private String model;
    private String modelYear;

    public CarBean(String make, String model, String modelYear)
    {
        this.make = make;
        this.model = model;
        this.modelYear = modelYear;
    }

    public String getMake()
    {
        return make;
    }

    public void setMake(String make)
    {
        this.make = make;
    }

    public String getModel()
    {
        return model;
    }

    public void setModel(String model)
    {
        this.model = model;
    }

    public String getModelYear()
    {
        return modelYear;
    }

    public void setModelYear(String modelYear)
    {
        this.modelYear = modelYear;
    }
}
Now that we have a model, let's change our JSP to iterate through an ArrayList of CarBeans instead of a simple string array (Example 2-10). The number of lines of code hasn't really changed, but hopefully the source code is far more readable using the JavaBean. (And yes, that pesky scriptlet code is still around. Once we get our Controller in place, we'll be able to replace it with something a bit more production-worthy.)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Looking Ahead...
As this application matures, the various pieces get pushed into different tiers. Instead of the servlet creating the CarBeans out of thin air, it will pass the request to an EJB. The EJB will eventually get the information out of a database. But for now we completed the first step toward a fully realized J2EE application.
If you are familiar with agile development methodologies, you know that having one working application in the hand is worth two that are still stuck in development. Even though the UI is just the tip of the iceberg in terms of the entire application, having this much in place is a huge milestone.
Nothing makes an application seem more real than a working set of screens, even if (as is the case here) it has nothing of substance behind the façade. It allows the user to see the program far more clearly and persuasively than index cards, white board drawings, or cocktail napkins. From the developer's perspective, it gives a clear idea of what blanks still need to be filled in (persistence, business logic, etc.).
Perhaps most importantly, it allows the UI to have the longest usage cycle. By the time the application is fully implemented, you and the users will have spent enough time working with the UI that all the usability and look-and-feel issues will have been long since been hammered out. As one of our customers said, "Because I was working with the screens from the very beginning, by the time the final application was delivered, I felt like I was already an expert."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Building and Deploying an EAR
In the last chapter we introduced you to web applications, but the web tier is just one part of the J2EE spectrum. In this chapter, we'll expand the JAW application from a simple WAR file into a full-fledged EAR.
We'll explore the different parts of an EAR file. We'll build a Common JAR containing classes that can be shared across all tiers of the application. Finally, we'll play with various Ant and XDoclet tasks to create our EAR and dynamically generate the deployment descriptors JBoss needs.
The WAR file is a convenient way to bundle up all pieces of a web application. All servlet containers know how to deploy a WAR file—they expand the bundle, look for the WEB-INF directory, and read the web.xml found there for further deployment instructions.
The EAR file provides the same type of functionality for a full-fledged J2EE application. JBoss expands the EAR, finds the required deployment descriptors, and proceeds from there.
An EAR is like a carton of eggs—it keeps everything organized. While the carton doesn't add any direct value to your omelet, it makes getting the eggs home from the store so easy that you wouldn't think about transporting eggs any other way.
Each egg in your EAR carton is a specific piece of the J2EE puzzle. These eggs (or JARs) come in three basic varieties called "modules":
Web module
A WAR file containing presentation tier components
EJB module
An EJB JAR file containing the middle-tier components (EJBs, MDBs, etc.)
Java module
A regular JAR file containing classes and libraries that are shared across the entire application. An application client JAR and a common JAR are two examples of Java modules.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
WARs Versus EARs
The WAR file is a convenient way to bundle up all pieces of a web application. All servlet containers know how to deploy a WAR file—they expand the bundle, look for the WEB-INF directory, and read the web.xml found there for further deployment instructions.
The EAR file provides the same type of functionality for a full-fledged J2EE application. JBoss expands the EAR, finds the required deployment descriptors, and proceeds from there.
An EAR is like a carton of eggs—it keeps everything organized. While the carton doesn't add any direct value to your omelet, it makes getting the eggs home from the store so easy that you wouldn't think about transporting eggs any other way.
Each egg in your EAR carton is a specific piece of the J2EE puzzle. These eggs (or JARs) come in three basic varieties called "modules":
Web module
A WAR file containing presentation tier components
EJB module
An EJB JAR file containing the middle-tier components (EJBs, MDBs, etc.)
Java module
A regular JAR file containing classes and libraries that are shared across the entire application. An application client JAR and a common JAR are two examples of Java modules.
An EAR can contain at least one of any of these modules. By the same token, any of them can be safely omitted if they aren't needed. Figure 3-1 shows the structure of an EAR file.
Figure 3-1: EAR file structure
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Application.xml
Just as a WAR file contains a web.xml deployment descriptor, an EAR file contains a file named application.xml. It is essentially a packing list, telling the J2EE server exactly what files the EAR contains and where you can find the files relative to the root of the EAR. The EAR file's META-INF directory stores application.xml.
Example 3-1 shows the JAW Motors application.xml file.
Example 3-1. application.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
             http://java.sun.com/xml/ns/j2ee/application_1_4.xsd"
         version="1.4">
  <display-name>JBossAtWorkEAR</display-name>
 
  <module>
      <web>
          <web-uri>webapp.war</web-uri>
          <context-root>jaw</context-root>
      </web>
  </module>
 
  <module>
      <java>common.jar</java>
  </module>
 
</application>
The elements in application.xml should be pretty self-explanatory. We are telling the application server the name of each JAR and what function it serves.
Notice that Web modules allow you to specify one other value—the <context-root>. Recall from the previous chapter that the context root is your web site's URL. If you deploy a simple WAR file, the name of the WAR will be used as the URL. When your WAR file is deployed inside an EAR, this element allows you to override the physical name of the WAR and use whatever URL you'd like.
Although not shown in this example, <security-role> is another important element in application.xml. The <security-role> element describes (what else?) the security roles used throughout a J2EE application for both web and EJB components. Defining security roles in application.xml provides a single place to set up J2EE declarative security without duplicating it in web.xml and ejb-jar.xml. The Security chapter describes <security-role> in greater detail.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Common JAR
In the previous chapter, we created a CarBean POJO to hold the various attributes of a car. We stored it in the WAR file because, well, you didn't have any other choice at that time. We should now reconsider the storage location for the CarBean to maximize its reuse.
By the end of this book, we will pull cars out of a database in the persistence tier, and hand them to objects in the business tier, which ultimately will pass them up to the presentation tier. An object that is shared across tiers is a perfect candidate for the Common JAR .
In addition to custom domain objects, the Common JAR is a great location to store common libraries such as Log4J or JDOM. While both WARs and EJB JARs have lib directories, they are best used for tier-specific libraries. For example, the JSTL JARs belong in the WAR—they have no other purpose than to support the creation of web pages. On the other hand, logging is something that happens throughout the codebase—it really belongs in a common JAR.
Let's factor our CarBean out of the WAR and into the Common JAR. In addition to moving directories, we're going to rename it to better describe its purpose in the application.
The suffix "Bean" is a bit overloaded: it includes JavaBeans, Enterprise Java Beans, Session Beans, Message-Driven Beans, JMX MBeans, and the list goes on. The design pattern that best describes the CarBean's function is a Data Transfer Object (DTO), so when we move the bean, we'll also rename it CarDTO. The source code will remain the same, but the name will give us a better idea about the true purpose of the class.
The previous chapter included only the webapp directory. If you change to the ch03/03a-ear directory, you'll see that we've expanded to a webapp directory and a common directory.
We also expanded from one to three build.xml files. Each subdirectory has its own build.xml, and the master build file lives in the top-level directory. The goal is to keep each portion of the application as autonomous as possible. Granted, most of the application will depend on the common sub-project , but by providing individual Ant scripts you have the opportunity to build each portion of the project separately.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Deploying the EAR
Let's make sure that the WAR files from the previous chapters don't end up conflicting with our EAR file. Delete jaw.war from the deploy directory before moving on. Now we're ready to drop in our newly created EAR file.
Deploying an EAR by hand is no different than deploying a WAR by hand. Copy jaw.ear to $JBOSS_HOME/server/default/deploy. Your JBoss console should let you know that it was deployed successfully, as in Example 3-6.
Example 3-6. JBoss console output showing a successful EAR deployment
22:37:55,659 INFO  [EARDeployer] Init J2EE application:
      file:/Library/jboss-4.0.1/server/default/deploy/jaw.ear
22:37:55,853 INFO  [TomcatDeployer] deploy, ctxPath=/jaw,
      warUrl=file:/Library/jboss-4.0.1/server/default/tmp/deploy/
      tmp25111jaw-ear.ear-contents/webapp.war/
22:37:56,159 INFO  [EARDeployer] Started J2EE application:
      file:/Library/jboss-4.0.1/server/default/deploy/jaw-ear.ear
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Adding a DAO
In that spirit, let's add another component that will pay dividends in future flexibility. Right now, your servlet is creating the car list each time a request comes in. This really isn't optimal. Servlets should deal with the mechanics of the HTTP request/response cycle. They shouldn't perform persistence tier tasks.
We aren't quite ready to install a database (that happens in the next chapter), but we can lay the groundwork by creating a Data Access Object (DAO). A DAO is a layer of abstraction—it hides the actual persistence specifics behind a common interface.
The DAO we create in this chapter still stores the DTO objects in a simple ArrayList. In the next chapter, the DAO will pull car data from a database that uses JDBC. In the chapter after that, it will use Hibernate (an Object/Relational Mapper) to do the same thing. By getting the DAO in place now, however, we'll be able to make these implementation changes without affecting presentation-tier code. Loose coupling and high cohesion comes to the rescue again.
The CarDAO provides a findAll() method that returns a List of CarDTOs. The source code in Example 3-7 can be found in the common directory in ch03b-dao.
Example 3-7. CarDAO.java
package com.jbossatwork.dao;

import java.util.*;
import com.jbossatwork.dto.CarDTO;

public class CarDAO
{
    private List carList;

    public CarDAO()
    {
        carList = new ArrayList();

        carList.add(new CarDTO("Toyota", "Camry", "2005"));
        carList.add(new CarDTO("Toyota", "Corolla", "1999"));
        carList.add(new CarDTO("Ford", "Explorer", "2005"));
    }

    public List findAll()
    {

        return carList;

    }
 }
The corresponding change in the ControllerServlet calls the newly created DAO in Example 3-8.
Example 3-8. ControllerServlet.java
// perform action
        if(VIEW_CAR_LIST_ACTION.equals(actionName))
        {
            CarDAO carDAO = new CarDAO();
            request.setAttribute("carList", carDAO.findAll());

            destinationPage = "/carList.jsp";
        }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using XDoclet
The last thing we'll do in this chapter is one more tiny bit of automation.
One of the most important parts of the WAR file is the deployment descriptor—web.xml. It lists each servlet and tells the servlet container how to deploy them. By maintaining this file by hand, you almost certainly guarantee that you will forget to update it when you add new components to your application. By using XDoclet in your build process, we can generate it automatically by using nothing but your source code and some well-placed comments.
XDoclet is a collection of custom Ant tasks that generate code during the build process. Sometimes XDoclet can generate the necessary code or deployment descriptor using just the source code. At other times, you'll need to add custom comments to nudge XDoclet along in the right direction.
We have only one servlet right now—ControllerServlet. Example 3-9 shows what your web.xml must contain to deploy this servlet correctly.
Example 3-9. web.xml
    <!-- servlet definition -->
    <servlet>
        <servlet-name>Controller</servlet-name>
        <servlet-class>com.jbossatwork.ControllerServlet</servlet-class>
    </servlet>

    <!-- servlet mapping -->
    <servlet-mapping>
        <servlet-name>Controller</servlet-name>
        <url-pattern>/controller/*</url-pattern>
    </servlet-mapping>
Look in ch03c-xdoclet/src for the new ControllerServlet source code in Example 3-10. Notice the XDoclet comments we've added.
Example 3-10. ControllerServlet.java
               /**
 * @web.servlet
 *    name="Controller"
 *
 * @web.servlet-mapping
 *    url-pattern="/controller/*"
 */
public class ControllerServlet extends HttpServlet
See how they correspond to the web.xml elements? Now let's look at build.xml to see the newly added XDoclet Ant tasks. We first need to create a couple of new variables, as in Example 3-11.
Example 3-11. Defining XDoclet variables in build.xml
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Looking Ahead...
We've covered a lot of ground in these first few chapters. We now have a single EAR file that encapsulates many moving parts of our J2EE application. We have automated the build process where it is appropriate, and set the stage for future growth.
In the next several chapters, we'll leave the web tier and move on to the persistence tier. We've stored our DTOs in an ArrayList for long enough—let's tackle saving them in a true database.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Databases and JBoss
Up to this point, this book has focused on the web tier. Now let's look at the persistence tier. This is where the application data is stored for the long term—for example, between server restarts.
Why use the phrase "persistence tier" instead of simply calling it the "database tier"? We certainly recognize that the probability of information ending up in a database approaches is somewhere close to 100%. J2EE pundits love pointing out that data could be stored in any number of manners—as flat files, XML, and even web services to remote servers. These types of storage are mentioned as alternatives, but we have yet to work on an application where they completely usurp the trusty database.
Instead, most modern persistence technologies deal with transforming relational database information into Java objects. These Object/Relational Mappers (ORMs) come in many flavors—commercial and open source—but make the same promise: to free the Java developer from the perils of converting ResultSets to ArrayLists of DTOs.
We continue to use the phrase "persistence tier" to remind us that many supporting services surround the inevitable database.
You should acknowledge one simple fact up front: if you deal with a relational database, all roads in one form or another lead to JDBC. Whether you write the code yourself or let an ORM write it for you, SQL INSERTs, UPDATEs, and DELETEs are the lingua franca of any database-driven application.
While Sun maintains that JDBC is not an acronym, it looks suspiciously like "Java DataBase Connectivity" to many seasoned programmers. It is the API that allows us to load up database Drivers, make Connections, and create Statements that yield ResultSets upon execution.
While nothing is intrinsically wrong with ResultSets, OO purists bristle at the thought of dealing with a semi-structured collection of strings and primitives. Java programmers are taught from a tender young age that JavaBeans and DTOs are the one true way to represent business objects. So to get from
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Persistence Options
You should acknowledge one simple fact up front: if you deal with a relational database, all roads in one form or another lead to JDBC. Whether you write the code yourself or let an ORM write it for you, SQL INSERTs, UPDATEs, and DELETEs are the lingua franca of any database-driven application.
While Sun maintains that JDBC is not an acronym, it looks suspiciously like "Java DataBase Connectivity" to many seasoned programmers. It is the API that allows us to load up database Drivers, make Connections, and create Statements that yield ResultSets upon execution.
While nothing is intrinsically wrong with ResultSets, OO purists bristle at the thought of dealing with a semi-structured collection of strings and primitives. Java programmers are taught from a tender young age that JavaBeans and DTOs are the one true way to represent business objects. So to get from ResultSets to DTOs, we must use hand-code methods that do the transformation for us, one car.setName(resultSet.getString("name")) at a time.
While this isn't terribly difficult, it does get tedious as the number of business objects and database tables grow. Maintaining two separate data schemas, one in Java and the other in SQL, strikes many as a flagrant violation of the DRY principle. The phrase "impedance mismatch" often comes up in JDBC discussions.
One potential way to avoid the problem of marshalling and unmarshalling JavaBeans is to remove the root cause—why not just create a database that deals natively with objects? On paper, object-oriented databases (OODBMS) seem to be the ideal solution to this problem. Sadly, OODBMSes have never gained any serious market share.
If you can't change the root data source—and relational databases are deeply entrenched in most long-term persistence strategies—your only other option is to come up with an API that manages the impedance mismatch: something that allows you to deal with native JavaBeans, and not only hides the JDBC complexity from you, but ideally entirely creates and manages the infrastructure.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JDBC
JDBC has been around nearly as long as Java itself. The JDBC 1.0 API was released with JDK 1.1. This is the java.sql package. JDBC 2.0 was released with JDK 1.2. It included both the Core package and what was called the Optional Package (javax.sql). The optional package brought with it better enterprise support for database connections, including connection pools and distributed transactions. JDBC 3.0 is the latest release, included with JDK 1.4.
If you've written JDBC code since the good old days, you'