BUY THIS BOOK
Add to Cart

Print Book $44.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £31.95

What is this?

Looking to Reprint this content?


Java Enterprise in a Nutshell
Java Enterprise in a Nutshell, Third Edition

By Jim Farley, William Crawford
With  Prakash Malani John Norman Justin Gehtland
Price: $44.95 USD
£31.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction
This book has arguably unreasonable goals. Its title alone invites raised eyebrows. Enterprise application development, on any platform, involves a wide array of tools to solve an equally wide array of issues and to manage several levels of complexity. How can you possibly hope to cover Java enterprise development tools in a single work, let alone in a nutshell?
Our approach to this lofty goal is simple. We have selected the key tools and APIs that enterprise architects and developers have found invaluable when working in the Java environment. Some of these are part of the core Java 2 Standard Edition (J2SE) environment; many of them are part of the larger Java 2 Enterprise Edition (J2EE) environment; many of them fall outside the Java standards but are useful and popular de facto standards within the Java community. For all of the tools covered, we provide a short but effective tutorial while also striving to cover enough critical detail that the material can serve as a quick reference as well. Along the way, in keeping with the "nutshell" concept of this series, we've had to edit brutally. Only tools and APIs that are proven in the industry while also being critical to success made the cut. Some things, useful and otherwise, had to be left by the wayside. But we hope that sifting effort alone will benefit you, since the book also serves as a guide through the sometimes confusing swirl of competing APIs, tools, and frameworks that make enterprise development daunting at times.
We've divided the material in the book into two main sections: tools that are part of the Java and J2EE standards and are managed under the auspices of the Java Community Process and tools that are not part of these standards but have been proven in practice and are de facto standards in the Java development community. Before we summarize the contents of these sections of the book, let's make it clear what we mean by "enterprise computing ."
The term "enterprise computing" raises many different images in people's minds: big, sterile-looking corporate data centers filled with humming servers ; complex financial systems stretching across the globe; elaborate multilevel software systems running a stupefying amount of code distributed across many servers, locations, companies, countries, even (in the case of NASA's Mars Rover project) planets.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enterprise Computing Defined
The term "enterprise computing" raises many different images in people's minds: big, sterile-looking corporate data centers filled with humming servers ; complex financial systems stretching across the globe; elaborate multilevel software systems running a stupefying amount of code distributed across many servers, locations, companies, countries, even (in the case of NASA's Mars Rover project) planets.
All of these images are true, to a degree. But they're all imprecise to a degree as well. Enterprise computing can be done on a single student's laptop as well as in a big corporate data center. It can be used in a small mom and pop business with a single storefront as well as in a huge multinational. It can be done just as effectively with a very small amount of code as it can with huge code repositories.
At its heart, enterprise computing is all about combining separate applications, services, and processes into a unified system that is greater than the sum of its parts. The rest is context that determines how you go about accomplishing this basic goal.
Anyone can write enterprise applications, not only because of the generalized nature of enterprise computing but also because the tools and techniques for developing enterprise systems have matured to the point that this domain is accessible to a much broader group of software developers. Many of the arcane details have been smoothed over by standards, well-defined APIs, and really powerful tools. This has made enterprise computing less scary and a lot more fun.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enterprise Computing Demystified
Enterprise computing has a reputation for complexity and, for the uninitiated, is often shrouded with mystery. Here are some reasons enterprise computing can seem intimidating:
  • Enterprise computing usually takes place in a heterogeneous network of systems, one in which the computers might range from large mainframes and supercomputers down to PCs, mobile laptops, and even handheld devices. The computers were purchased at different times from a variety of different vendors and run two, three, or more different operating systems.
  • A variety of server applications run on top of the heterogeneous hardware. An enterprise might support application servers from three different companies, each of which covers a different functional subset of the enterprise and each of which includes different, incompatible interfaces and extensions.
  • Enterprise computing involves the use of many different protocols and standards. Some standards overlap in small or significant ways. Many have been extended in various vendor-specific, nonstandard ways. Some are quite old and use a vocabulary and terminology that date back to an earlier era of computing. This creates a confusing alphabet soup of acronyms and abbreviations.
  • Enterprise computing has only recently emerged as an integrated discipline of its own. Although enterprise development models are becoming more cohesive and encompassing, many enterprises are still left with lots of "legacy systems" that are aggregated in an ad hoc way.
Java helps to alleviate these intimidating aspects of enterprise computing. First, since Java is platform-independent, the heterogeneous nature of the network ceases to be an issue. Second, the J2EE framework forms a single, standard layer on top of various proprietary or vendor-enhanced APIs . For example, the Servlet API and the JavaServer Pages API comprise a single, standard, well-defined way to implement web interfaces, regardless of the application server, web server, operating system, or hardware being used. Third, the Java and J2EE frameworks provide an excellent foundation on which you can layer other, nonstandard but compatible tools. Standards can cover only part of the enterprise application landscape, and there will always be valuable utilities developed by the business and developer communities that fall outside of the standards. A standardized framework provides a stable, formally managed backdrop for using these utilities without compromising the portability promises of Java and J2EE. Finally, recall that many enterprise protocols and standards were developed before the days of object-oriented programming. The object-oriented power and elegance of the Java language make the Java Enterprise APIs simpler, easier to use, and easier to understand than the non-Java APIs and protocols upon which they are layered.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Standard Java Enterprise APIs
The J2EE standard framework provides support for a number of the most commonly used distributed computing technologies and services. These APIs serve as building blocks for enterprise applications. In this section, we group them into rough functional categories and discuss how they are covered in this book. In the section that follows this one, we discuss some key, but nonstandard, enterprise APIs and tools that facilitate the assembly of these enterprise components into applications. At the end of the chapter, we describe an enterprise computing scenario that illustrates how these APIs and tools can be used together to produce an enterprise application.
Two essential technologies for enterprise application development are XML and security services.

Section 1.3.1.1: Java API for XML Processing (JAXP)

XML is not strictly an enterprise-focused tool. XML is useful in all kinds of contexts, enterprise and otherwise. We've included it in this book, however, because XML is now such a fundamental, all-purpose tool that it touches nearly every level of enterprise application development, from basic datafile formats to interprocess communications to user interface representations.
The Java API for XML Processing (JAXP) (defined in JSR 005) is the standard API for consuming and producing XML in Java. Application servers compliant with J2EE 1.3 and later must include a compliant JAXP implementation. JAXP provides a pluggable API that supports both SAX and DOM parsing of XML content, as well as XSLT-based transformations of XML. JAXP 1.2, the version specified in the J2EE 1.4 specification, supports the SAX 2 and DOM 2 parsing APIs, as well as the XSLT 1.0 transform API. JAXP is covered briefly in Chapter 7. The JAXP APIs are also covered in Java in a Nutshell by David Flanagan (O'Reilly).

Section 1.3.1.2: J2EE security

Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
De Facto Standard Enterprise Development Tools
The Java community members involved in defining the J2EE platform and its supporting standard enterprise APIs would be the first to admit that it was never their intent to create standards for every element of enterprise development. If there were only one right way to do everything, there wouldn't be much room for creativity (or profit, for that matter). J2EE covers a critical mass of the capabilities needed when building and running enterprise applications. It standardizes those things that are required in order to make enterprise applications portable across application servers and support systems, to allow vendors to integrate their services into the Java environment in a standard way and to prevent enterprise developers from wasting their valuable time re-creating utilities that really should be plumbing, enabling them to focus their efforts on the business logic and user interfaces of their systems.
In addition to the standard Java Enterprise APIs discussed earlier, an enterprise developer typically finds herself turning to a set of other support tools and extension APIs in order to be efficient and effective in building enterprise systems. These tools and APIs fill the gaps left by the standard enterprise Java APIs. Sometimes these gaps are intentional (e.g., "it doesn't make sense to standardize an API for X"). Other times the gaps are temporary, because a standard hasn't been defined yet for a particular area.
In the second part of this book, we provide tutorials on popular, effective tools and APIs that are typically used when building enterprise Java systems. Choosing the tools to include in this section was difficult in many cases, because so many viable, effective options are available in some areas. But we chose tools and APIs based on the size of their respective user communities, the effectiveness of their solutions, and the expected longevity of the tools and APIs relative to other options.
Readers will quickly realize that all of the tools chosen for this section of the book are open source tools (see
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
An Enterprise Computing Scenario
The previous sections have been rapid-fire introductions to the Java Enterprise APIs that are part of the J2EE framework as well as a set of key de facto standard tools used commonly in the Java Enterprise space. Don't worry if you didn't understand all the information presented there: the rest of the chapters in the following two parts of the book cover the APIs in more detail. The important message you should take from this chapter is that the Java Enterprise APIs are building blocks that work together to enable you to write distributed Java applications for enterprise computing. The computing infrastructure of every enterprise is unique, and the Java Enterprise APIs can be combined in any number of ways to meet the specific needs and goals of a particular enterprise.
Figure 1-1 shows a schematic for a hypothetical enterprise. It illustrates some of the many possible interconnections among distributed services and shows some of the Java Enterprise APIs that facilitate those interconnections. The figure is followed by example scenarios that demonstrate how the Java Enterprise APIs might be used to solve typical enterprise computing problems. You may find it useful to refer to Figure 1-1 while reading through the scenarios, but note that the figure doesn't illustrate the specific scenarios presented here.
Figure 1-1: The distributed computing architecture of a hypothetical enterprise
CornCo Inc. runs a successful catalog-based mail-order business selling fresh flavored popcorn. They want to expand into the exciting world of online sales. Here's how they might do it:
  1. A customer visits the company's web site, http://www.cornco.com, and uses a web browser to interact with the company's web server. This allows the customer to view the company's products and make selections to purchase.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Other Enterprise APIs
We have decided not to include several enterprise APIs in this nutshell book, for a variety of reasons. In most cases, it was due to prioritizing space for other tools that we felt were more important to a larger population of readers.
In the area of web services, the Java API for XML Registries (JAXR) provides a standard API for interacting with web service registries implemented using UDDI or ebXML, standard web service registry protocols. JAXR is not covered here, because despite the initial enthusiasm over web services and the current maturity of basic web service tools and APIs, the practice of creating web service registries remains a relatively niche concern. Large organizations creating broad service-oriented architectures (SOAs) may find effective use for UDDI and ebXML registries, but for many contexts, web services talking SOAP and described using WSDL are enough, so we've kept our coverage to JAX-RPC and SAAJ. Readers are encouraged to consult Java Web Services by Dave Chappell and Tyler Jewell (O'Reilly) for details on using JAXR.
The Java Management Extensions (JMX) provide a standard framework for creating distributed management and monitoring capabilities. The things being managed and monitored could be applications, devices, external services, or any critical enterprise capability. We've omitted JMX and related standards like the J2EE Management specification from the book because of their somewhat narrow domain of use. Full details on JMX can be found in Java Management Extensions by J. Steven Perry (O'Reilly).
Enterprise systems can be global not only in terms of server locations but also in terms of user population. Web applications, by definition, are potentially accessible worldwide, and in some cases it is important to consider the need to internationalize and localize your applications. Internationalization refers to the ability of systems to behave properly when used with different languages and display standards. Localization refers to the ability of an application to adjust itself to local conditions, such as time zone and personal display preferences. In the interest of space, we do not discuss the topics of internationalization or localization of Java applications (enterprise or otherwise). The interested reader, however, should refer to
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: Application Assembly and Deployment
In any enterprise framework, it's important to understand not just the APIs and tools that are needed to develop application code but also the model that the framework uses for assembling and deploying the components of applications. Assembly of an application or component is the process of collecting all of the elements required (source code, datafiles, and configuration files) into a structured format that can be deployed to the server environment. Deploying a component or application is the process of actually installing the runnable code in the runtime environment, which involves making the code available to the server and resolving resource references in the assembly with the resources actually available on the server.
Assembly and deployment are usually considered separate activities for several reasons. Perhaps most importantly, assembly is focused on the nature of the application itself while deployment is focused on the integration of the application with a specific runtime environment. Assembly of code, therefore, is more easily standardized within a given enterprise framework. Archive structures and configuration file formats can be specified in a generic way, including references to external resources like databases and messaging services. Deployment, on the other hand, is more context-dependent. The type and configuration of the runtime environment are going to determine how each deployment will be carried out. The assembly itself will need to be installed in the runtime environment in different ways, depending on the architecture and configuration of the server. If an application requires a specific resource (as specified in its assembly), and a suitable resource is not available in the runtime environment, it will need to be provisioned before the application can be deployed. The physical steps needed to perform these deployment tasks vary for different runtime environments although the same application assembly is being deployed to each.
J2EE is no different in this regard. As we'll see in later chapters of this book, J2EE supports various types of application components (web-based components built using the Java Servlet, JavaServer Pages, and JavaServer Faces APIs; business components built using the Enterprise JavaBeans APIs; and so on). The J2EE specifications include standard archive formats and configuration file formats for application and component assemblies. These configuration files, called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
J2EE Application Assembly Model
First, let's get the J2EE terminology straight. Figure 2-1 depicts the assembly model for J2EE applications. J2EE applications are composed of one or more components. A component is a functional element of an application that runs within a container and makes use of the runtime services provided by the container. These runtime services might be security management services, transaction management services, lifecycle services, or others, depending on the type of component and the type of container. A component consists of one or more Java classes that implement the component, along with any component-specific resources like properties files, images, and the like. J2EE components (and their containers ) come in five flavors: application clients , applets , web, EJB, and resource adapters . Each type of container is capable of providing a specific set of APIs and runtime services to its corresponding components.
J2EE components are grouped together and deployed in modules , which are collections of components of the same type, to be run inside the corresponding container type. A module contains all of the component-specific classes, plus any
Figure 2-1: J2EE assembly model (conceptual)
class libraries needed by the components and other cross-component resources, such as datafiles, HTML documents (for web components), and image files. Each module also contains a standard XML deployment descriptor that provides descriptive information, external resource references, and configuration details about each component it contains. If required, a module can also contain application server-specific details, such as configuration files, classes, and resources that are required by a particular application server. Most application servers, for example, allow you to specify additional configuration parameters, not included in the standard J2EE deployment descriptors , in separate configuration files. The application server vendor dictates the format for these files and where they should be included in the module archive. Modules are packaged in the form of jar files, with the deployment descriptor, classes, class libraries, and other resources placed in specific locations in the jar file.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Component Modules
A component module is the smallest unit of deployment in the J2EE deployment model. A module is simply a jar file containing all of the bits and pieces that define a set of components. Each module contains components of the same type so that they can be easily delegated to the containers that handle them.
Each component module is packaged as a jar file with a specific layout for the elements that make up the components. Table 2-2 summarizes the different module jar files and deployment descriptors used for the different J2EE component types:
Table 2-2: Component module format summary
Component type
Module jar file suffix
Deployment descriptor filename and location
Web
.war("web archive")
WEB-INF/web.xml
Enterprise JavaBeans
.jar
META-INF/ejb-jar.xml
Applet
.jar
Not applicable
Application client
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 Assemblies
Once we have our components assembled into the appropriate modules, each with a deployment descriptor, we can assemble an application by bundling the component modules along with an application deployment descriptor into an enterprise application archive (ear) file.
Like component modules, an application archive is just a jar file with files stored in specific locations, as dictated by the J2EE specifications. The deployment descriptor is stored as META-INF/application.xml in the jar file, and component modules are placed in the jar and referenced in the application descriptor using their location relative to the top of the application archive. The full syntax of the application deployment descriptors can be found in Appendix A.
Application deployment descriptors are simpler in structure, because they primarily serve to assemble component modules that have their own deployment information. The application deployment descriptor contains the following categories of information:
Application descriptive information
Similar to component modules, applications can also have descriptive information in their deployment descriptors. The application can be given a name and a description that can be displayed in management tools, for example.
Figure 2-5: Web module deployment descriptor
Module references
Each component module to be included in the application must be referenced in its own <module> element in the application.xml file. The module reference indicates the location of the module jar file in the application archive. In the case of web modules, the module can also be given a web context root in the application descriptor. This context root is used as the base of URLs mapped to the components in the module.
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 J2EE Applications
Once all of the J2EE modules have been packaged into their respective jar files, each with a deployment descriptor, and an application archive has been created with its own deployment descriptor, you still need to actually deploy the application to a J2EE application server. The deployment of an application (or even a single module) typically involves the steps described in the remainder of this section. In each case, we'll demonstrate the task using a JBoss application server and discuss how these tasks might be done in different ways in different application servers.
When you develop and package a set of components, you might imagine that the module should remain unchanged when it's deployed as part of an application. But there can be local environmental issues that force an application deployer to adjust the deployment descriptors . Some configuration parameters placed in environment entries may need to be adjusted, for example. A shopping cart web component might be delivered as part of an application with a JNDI environment entry that specifies the maximum number of line items the cart allows, with a default setting. This default value may need to be changed at deployment time to meet the needs of a particular user population (e.g., the application is being deployed for departmental administrators who require a much larger number of line items on average when ordering).
In addition to these configuration values, you may want to resolve component references directly in the module deployment descriptors. In our profile application, for example, we have a web component (our JSP for viewing profiles) that references the profile EJB component in its deployment descriptor because it makes use of it at runtime. As we mentioned earlier in this chapter, it's possible to directly resolve these references without setting up a link to a named asset in the server's JNDI service. In this case, we would alter the web module deployment descriptor to specify the component that the EJB reference should resolve to:
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: Java Servlets
Over the last few years, Java has become the predominant language for server-side programming. This is due in no small part to the Java Servlet API , which provides a standard way to extend web servers to support dynamic content generation. In terms of enterprise computing, servlets are a natural fit if you are using the Web as your deployment platform. You can take advantage of web browsers as universally available thin clients using the web server as middleware for running application logic. Under this model, the user makes a request of the web server, the server invokes a servlet designed to handle the request, the servlet fulfills the request, and the result is returned to the user for display in the web browser.
While this sounds like every other dynamic content technology (such as CGI, ISAPI, ASP, PHP, and the like), servlets have some major advantages. For one, servlets are persistent between invocations, which dramatically improves performance relative to CGI-style programs. Servlets are also 100% portable across operating systems and servers, unlike any of the alternatives. Finally, servlets have access to all the APIs of the Java platform, so, for example, it is easy to create a servlet that interacts with a database, using the JDBC API (see Chapter 8).
The Servlet API also provides the basis for programming with JavaServer Pages (see Chapter 4), Struts (see Chapter 19), and Java Server Faces (see Chapter 5). In fact, if you use one of these frameworks to structure your application, you may never need to write a servlet at all. But since JSP, JSF, and Struts are all designed to work as components of larger applications, you can mix your own servlets, filters, and session management into your framework-based applications, and that makes a good knowledge of the Servlet API essential for advanced enterprise development.
Version 2.3 of the Servlet API is a required component of J2EE Version 1.3. A small update, Version 2.4, came out in 2003 and is part of the J2EE Version 1.4 specification. Since the two versions are very similar (and there are still a lot of Version 2.3 applications out there), you can assume that anything in this chapter applies equally to both versions unless we specifically say otherwise.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting a Servlet Environment
You need a servlet container to run servlets. A servlet container uses a Java virtual machine to run servlet code as requested by a web server. The servlet container is also responsible for managing other aspects of the servlet lifecycle : user sessions, classloading, servlet contexts, servlet configuration information, servlet persistence, and temporary storage.
Because Tomcat is the reference implementation for the Servlet API, all the examples in this chapter have been tested with it. Tomcat 4.x supports the 2.3 API, and Tomcat 5.x supports the 2.4 API. Since Tomcat falls under the Apache umbrella, distribution is free, and you can download a copy (including, if you like, full source code) from http://jakarta.apache.org.Binary installations are available for Windows and several Unix flavors.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Servlet Basics
The Servlet API consists of two packages, javax.servlet and javax.servlet.http. The javax is left over from an earlier stage of Java package naming conventions. As mentioned (and as indicated by the fact that this chapter appears in Part I of this book), servlets are a standard part of J2EE.
When a client makes a request involving a servlet, the server loads and executes the appropriate Java classes. Those classes generate content, and the server sends the content back to the client. In most cases, the client is a web browser, the server is a web server, and the servlet returns standard HTML. From the web browser's perspective, this isn't any different from requesting a page generated by a CGI script or, indeed, a static HTML file. On the server side, however, there is
Figure 3-1: The servlet lifecycle
an important difference: persistence. Instead of shutting down at the end of each request, the servlet can remain loaded, ready to handle subsequent requests. Figure 3-1 shows how this all fits together.
The request processing time for a servlet can vary, but it is typically quite fast when compared to a similar CGI program. The real performance advantage of a servlet is that you incur most of the startup overhead only once. Most of the I/O-intensive resources (such as database connection pools) your application will need can be created by the servlet container at startup and shared by all your servlets. Instead of connecting to the database—or just loading your code—thousands of times a day, the container loads it only once. When the container loads a servlet for the first time, it calls the init(ServletConfig) method, which is allowed to complete before the servlet is asked to respond to any requests. After the init() method runs, the servlet container marks the servlet as available. For each incoming connection directed at a particular servlet, the container calls the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Web Applications
Now that we've seen a basic servlet, we can step back for a moment and talk about how servlets are integrated into the servlet container. A web application consists of a set of resources, including servlets, static content, JSP files, and class libraries, installed in a particular path on a web server. This path is called the servlet context, and all servlets installed within the context are given an isolated, poperate in, without interference from (or the ability to interfere with) other software running on the server.
A servlet context directory tree contains several different types of resources. These include class files and jar files (which aren't exposed to clients connecting via web browsers), JSP files (which are processed by the JSP servlet before being fed back to the client), and static files, such as HTML documents and JPEG images, which are served directly to the browser by the web server.
The context has a virtual component, too. For each context, the servlet container will instantiate separate copies of servlets and will create a private address space that can be accessed via the ServletContext class. Servlets running in the same context can use this class to communicate with each other. We'll discuss this more later.
The simplest servlet installations create just a single context, rooted at /, which is the top of the web server path tree. Servlets and static content are installed within this context. Most of the time, you'll create multiple servlet contexts , rooted lower down on the directory tree. A catalog application, for example, could be rooted at /catalog, with all of the application paths below the context root.
If you write a web application that will be installed on multiple web servers, it isn't safe to assume the context root will be fixed. If the path of a resource within your application is /servlet/CatalogServlet, and it's installed within the /catalog context, rather than writing:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Servlet Requests