TE AM FL Y
Team-Fly
®Dear Valued Customer,
We realize you’re a busy professional with deadlines to hit. Whether your goal is to learn a new technology or solve a critical problem, we want to be there to lend you a hand. Our primary objective is to provide you with the insight and knowledge you need to stay atop the highly competitive and ever- changing technology industry.
Wiley Publishing, Inc. offers books on a wide variety of technical categories, including security, data warehousing, software development tools, and networking - everything you need to reach your peak.
Regardless of your level of expertise, the Wiley family of books has you covered.
• For Dummies – The fun and easy way to learn
• The Weekend Crash Course –The fastest way to learn a new tool or technology
• Visual – For those who prefer to learn a new topic visually
• The Bible – The 100% comprehensive tutorial and reference
• The Wiley Professional list – Practical and reliable resources for IT professionals
Our commitment to you does not end at the last page of this book. We’d like to open a dialog with you to see what other solutions we can provide. Please be sure to visit us at www.wiley.com/compbooks to review our complete title list and explore the other resources we offer. If you have a comment, suggestion or any other inquiry, please locate the “contact us” link at www.wiley.com.
Sincerely,
Richard K. Swadley
Vice President & Executive Group Publisher Wiley Publishing, Inc.
WILEY
advantage
In the book that you now hold in your hands, Darren Broemmer shares best practices and lessons learned for J2EE development. As you design and build a banking application with J2EE and design patterns, you'll also utilize metadata-driven configurable foundation components to help automate much of the development for Web-based business applications. And of course, the tools and technologies used to construct the sample application are not from any one vendor, but best of breed—Jakarta Struts, Servlets, JSP, XML, EJB, UML, WebLogic, WebSphere, and many more.
Thank you for your support and we look forward to hearing from you and serving your needs again in the future.
Java TM Design Patterns, Automation, and Performance
Darren Broemmer
Wiley Publishing, Inc.
Publisher: Bob Ipsen Editor: Theresa Hudson
Developmental Editor: Kenyon Brown Editorial Manager: Kathryn A. Malm Managing Editor: Pamela Hanley New Media Editor: Brian Snapp
Text Design & Composition: Interactive Composition Corporation
Designations used by companies to distinguish their products are often claimed as trade- marks. In all instances where Wiley Publishing, Inc., is aware of a claim, the product names appear in initial capital or ALL CAPITAL LETTERS. Readers, however, should contact the ap- propriate companies for more complete information regarding trademarks and registration.
This book is printed on acid-free paper.
Copyright © 2003 by Darren Broemmer. All rights reserved.
Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspointe Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail: [email protected].
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages.
For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Library of Congress Cataloging-in-Publication Data:
ISBN 0-471-22885-0
Printed in the United States of America
10 9 8 7 6 5 4 3 2 1
for all of their love, support, and encouragement.
vii
Acknowledgments x
About the Author xi
Introduction xii
Overview of the Book and Technology xii
How This Book Is Organized xx
Who Should Read This Book xxiii
Tools You Will Need xxiii
What’s on the Web Site xxiv
Summary xxiv
Chapter 1 Building Business Applications with J2EE 1 Elements of Transactional,
Web-Based Business Applications 2
The Reference Architecture 4
The J2EE Platform Approach 9
The Model-View-Controller Architecture Approach 16 Best Practices for Building Business Applications
with J2EE 20
Summary 21
Chapter 2 The Business Object Architecture: Design Considerations 23 Business Objects in a Banking Application 25
Elements of Business Objects 26
Design Considerations 29 Best Practices for Designing Business Objects 50
Summary 53
Chapter 3 Building Business Objects: Managing Properties
and Handling Errors 55
Managing Properties 55
Value Objects and Lightweight Business Objects 83 Object Validation and Error Handling 87 Best Practices for Implementing Business Objects: Part One 102
Summary 103
Chapter 4 Building Business Objects: Persistence, Relationships,
and the Template Method Pattern 105
Object Persistence 105
The Base Class as a Template 159
Overall Business Object Metadata Approach 168
Data Caching 174
Best Practices for Implementing Business Objects: Part Two 185
Summary 188
Chapter 5 The Service-Based Architecture: Design Considerations 189 Elements of Service-Based Components 193
Design Considerations 196
Best Practices for Designing Service-Based Components 207
Summary 208
Chapter 6 Building Service-Based Components 209
The Actual Service Interface 209
An Implementation for Argument Lists 210 The Session Bean as a Component Wrapper to the Service 215 Responsibilities of the Service Component 221
Update Service Examples 225
Updating Multiple Business Objects 233
The New Customer Service 234
Data Retrieval Services 240
Building Generic, Reusable Services 251 Implementing the Controller Pattern in Services 253 Best Practices for Implementing Service-Based
Components 255
Summary 257
viii Contents
Chapter 7 The User Interaction Architecture: Design
Considerations and an Overview of Jakarta Struts 259 Elements of the User Interaction Architecture 261
Design Considerations 265
An Overview of Jakarta Struts 284
Best Practices for Designing the User
Interaction Architecture 298
Summary 300
Chapter 8 Building the User Interaction Architecture 301
The Change Address Page 301
The Change Address JSP 307
The View Accounts Page 332
The New Customer Wizard 342
A Template for the Action Class 362
Web Services 369
Best Practices for Implementing the
User Interaction Architecture 371
Summary 372
Chapter 9 Strengthening the Bank Application: Adding Security
and Advanced Functionality 375
Application Security 375
Interesting Aspects of the Bank Application 392 Best Practices for Advanced Web Application Development 417
Summary 418
Chapter 10 Performance 421
Overall Performance Approach 421
Performance in J2EE Applications 430 Best Practices for J2EE Performance Engineering 440
Summary 442
Chapter 11 Moving toward Reuse in the Reference Architecture 443 Common Roadblocks and Corresponding Best Practices 444 Reuse in the Reference Architecture 452 The Strategic View of the Architecture 454 Best Practices for Moving toward Reuse 456
Summary 457
Bibliography 459
Index 461
I owe countless thanks to my parents, John and Joan, Shirley and my late father Gary, for always being there and giving so much of themselves to help me. Without question, this book would not have been possible without everything that they have done for me. Special thanks also goes to John Abbey, Jeff Nelms, and Ken Young for reviewing the chapters, providing their insight, and contributing to this effort. John and I have collaborated for years on J2EE development and had many a lively and entertaining discussion on the topic. Likewise, Jeff and I have debated the finer points of business objects many times and much of the performance slant in this book can be traced back to his influence. Ken’s early feedback helped to shape the perspective that the book eventually took. I would also like to recognize Ron Carden for his influence in my work and the development of this material. Another person who made this book pos- sible is my wife Caroline who enthusiastically supported me throughout the effort. I would also like to acknowledge Bill Hough who unquestionably supported this effort.
Special thanks to Jack Greenfield, Terri Hudson, and all the folks at Wiley for their sup- port and help in putting this book together. Finally, thanks to God through whom all things are made possible.
Darren Broemmer September 2002
Acknowledgments
x
TE AM FL Y
Team-Fly
®xi Darren Broemmer is an application architect working on next-generation J2EE soft- ware solutions in the mortgage industry at Freddie Mac. His previous work includes architecture, development, and management experience in Internet and client-server systems implementations for consulting clients in North America, Europe, and the Middle East. Darren specializes in Java and J2EE technology and is the coinventor of a Java application development framework called jPylon, a set of reusable, extensible software components based on J2EE. JPylon was chosen to be a part of the Sun Microsystems ONE Studio Developer Resources program (formerly Forte for Java Extension Partners Program). Throughout his career, Darren has regularly consulted with projects on best practices for J2EE development and has spoken at corporate con- ferences about jPylon and J2EE technology. When he is not busy thinking of ways to abstract and automate software development, Darren tries to stay in shape by playing basketball and running, although he will never be able to keep up with his wife at Ultimate Frisbee.
Java 2 Enterprise Edition (J2EE) technology is becoming a pervasive platform for the development of Internet-based, transactional business applications. It provides a robust development platform upon which to build flexible, reusable components and applications. It is a powerful standard that is well-suited for Internet-based applica- tions because it provides many of the underlying services such as HTTP request pro- cessing (Java servlet API), transaction management (Enterprise JavaBeans), and messaging (Java Message Service), just to name a few. However, J2EE is also a complex and changing standard that leaves the technologist with many design decisions and performance considerations. Each component service adds a level of overhead to the application processing that must be considered. Additionally, there are a number of common business logic functions, such as error handling, that must be designed and developed for each component and application.
An application development effort using J2EE should give careful consideration to the services provided by the platform and how application components can best utilize them. There are a number of best practices one should consider in order to be highly effective in building J2EE components and integrating them into applications. These practices include evaluating and selecting the right set of software components and services to do the job. This is no different than in other professions; a carpenter or a steelworker both use an architecture plan to build things, although the tools they use to do so are quite different. A scalable, modular architecture built upon J2EE will likely comprise a selection of the appropriate set of J2EE services combined with a custom foundation of common business logic functions.
Overview of the Book and Technology
This book will supply a set of best practices for J2EE software development and then use them to construct an application architecture approach referred to as the ref- erence architecture. The reference architecture will provide a basis for rapidly building
Introduction
xii
transactional business applications using J2EE technology. The design and implemen- tation of the reference architecture is based on a set of guiding principles that will be used to optimize and automate J2EE development.
Guiding Principles of the Reference Architecture
The goal of constructing the reference architecture is to create a development environ- ment that can be used to build applications faster and with better performance, qual- ity, and reusability. The following set of guiding principles are used to accomplish these goals:
Applying proven design patterns to J2EE Automating common functions
Using metadata-driven, configurable foundation components Considering performance and scalability
These principles are essential in driving the architecture and building the founda- tion for development. These concepts will be discussed throughout this book in detail and applied to each segment of the J2EE architecture. Much of software development in general and J2EE development in particular can be optimized and automated through these concepts and their realization in the form of common foundation logic.
Solid analysis of design choices as input to the architecture and application compo- nents is essential in order to provide solutions that balance the needs of rapid devel- opment, faster performance, higher quality, and greater reusability.
Figure I.1 shows the inputs and outputs of the architecture. This diagram essentially represents the guiding principles and the benefits that can be derived from applying them to application development.
These principles provide the motivation and the basis for the approach to this study of developing applications using J2EE. Each aspect of the enterprise architecture within J2EE will be studied for its behavior and characteristics. By using this information and applying the development principles and best practices, you can create an approach to effectively use the technology to reach our application development goals.
The goals at the right side of Figure I.1, such as flexibility and reusability, should be considered and addressed from the beginning of any software development project.
These types of goals are realized at two different levels: the software architecture level described earlier and the application component design. The reference architecture will guide much of the application design, so it is important to understand and distin- guish these levels before undertaking enterprise software development. Each of the two levels will provide different types of benefits to both the end users and the devel- opment organization.
Applying Proven Design Patterns
A design pattern is a defined interaction of objects to solve a recurring problem in software development. There are a number of documented design patterns (E.
xiv J2EE Best Practices: Java Design Pattens, Automation, and Performance
Gamma, R. Helm, R. Johnson, J. Vlissides, 1995. Design Patterns. Boston, MA:
Addison-Wesley) that represent proven solutions that you can use to solve common problems in object-oriented (OO) development. You can also apply many of these pat- terns to the J2EE architecture. One example is the concept of a service within the Service-Based Architecture. The service component layer of the reference architecture will resemble both the Façade and Mediator patterns (Gamma et al. 1995). The service component provides a simple interface to the client and decouples the presentation components (JavaServer Pages or servlets) from the back-end business logic compo- nents. This provides the benefit of increased reusability and a simplified view of the world from the client perspective. If you add a standard interface to the service com- ponents, you can now implement the Command pattern (Gamma et al. 1995) from a front-end component. This allows you to build a generic, configurable controller com- ponent in the front end that invokes these standardized back-end services.
If you apply these well-documented, proven design patterns to J2EE architecture, you will see that the stateless Session Bean is the perfect implementation for the Service-Based Architecture. This becomes the Session-Façade pattern (D. Alur, J. Crupi, D. Malks. 2001. Core J2EE Patterns. Mountain View, CA: Sun Java Center), an imple- mentation of the Façade pattern applied to a Session Enterprise Java Bean. If you con- sider a Session Bean component merely to be a wrapper around your service object that adds the ability to distribute the service and manage transactions around it, you Figure I.1 Architecture Principles and Benefits.
Business Logic Foundation Java/J2EE Application Server
Application Components End-User Applications
Software Architecture
Applying Design Patterns
Automating Common Functions
Metadata-Driven Components Consider Performance Throughout the Process
Analysis of Design Choices
Best Practices
Application Development
Benefits
Flexibility Reusability High-Performance
Applications Quality Product Rapid Application
Development
utilize the J2EE component-based services without changing the object-oriented view of the world very much at all. In the case of stateless Session Beans, you also gain these benefits without adding much overhead to the processing time. The session façade act- ing as an EJB component wrapper around a service implementation object is referred to as the Service Component pattern in the reference architecture.
Figure I.2 illustrates the UML representation of this service component pattern.
The business objects and presentation components also contain numerous examples of proven design patterns that can be applied. The Template Method pattern (Gamma et al. 1995) provides an excellent mechanism for providing extensible foundation com- ponents for both business objects and service objects. In the case of business objects, it provides a template for common operations such as a save operation to cause the object’s data to persist in the database. The base class, or template, provides hooks for subclasses, the specific business objects, to implement validation rules and presave or postsave logic. Enterprise JavaBeans uses a number of design patterns applied to the Java language. Some of them are variations of existing patterns that use Java interfaces, such as with Entity Beans. Entity Beans must implement a common interface javax.ejb.EntityBeanthat provides hooks for insert, update, and delete logic.
Each architecture layer discussed builds on these existing patterns and looks at some additional patterns that provide flexibility and reusability within the software archi- tecture on top of J2EE.
Figure I.2 UML Diagram of Service Component Pattern.
MyBusinessObject1 Attribute1:String Attribute2:String businessMethod1() businessMethod2()
MyBusinessObject2 Attribute1:String Attribute2:String businessMethod1() businessMethod2() ServiceImpl
doService()
ServiceEJBWrapper
executeService()
Business Object Packages
xvi J2EE Best Practices: Java Design Pattens, Automation, and Performance
Automating Common Functions
The approach of automating common functions provides a number of benefits:
Time is not wasted on monotonous, error-prone tasks.
A higher-quality product through better-tested software; there is less total code to run through and it gets hit on every request; in essence, the foundation of much of the processing becomes a black box process with inputs.
Automated functions and their common interfaces make it easier to develop and maintain consistent software across the application.
Even with easy-to-use APIs such as the Java servlet API, there are still many func- tions that must always be done in an application. For example, one of the common elements of business applications is the ability to process user form submissions. On each of these requests, the data from the form submission needs to be read out of the HttpServletRequestobject, packaged in some data structures, and sent to the requested service or back-end function. One alternative is to write a custom servlet or JSP to handle every form on all pages. This usually isn’t very efficient because the num- ber of forms in a typical business application is relatively high. You might find that the logic to handle each form is repetitive and even has the same blocks of code in it. The other alternative is to abstract the basic flow of handling a form request and put it into a common servlet that can be used by all of the Web pages that have forms. Using a configuration service, you could define each form, its input data, and a service that should be used to process the request. Almost any function or process that is repeatable is a candidate for automation. This book looks at the nature of transactional Web ap- plications in order to define a set of common elements that can be automated. As it turns out, due to the nature of Web applications and J2EE application architectures, many of these common elements need to be implemented for any given application. A set of configurable foundation components that implement these functions will increase both the quality and quantity of application functionality built on the reference architecture. As this book goes through the process of discussing the set of common elements and applying them to the Java platform, additional requirements for this foundation layer will be flushed out. Some basic work can be done at this level that provides immense value in meeting the overall goals of a scalable, modular architecture.
A set of configurable foundation components that automate basic elements of an ap- plication is often referred to as a framework. Building upon an earlier principle, many of these foundation components will be implemented using proven object-oriented design patterns. These framework components and patterns are what make up the ref- erence architecture that will be used to rapidly develop quality J2EE applications. As many developers know, there is a gap between the total sum of services needed to de- velop just purely application-specific logic and those that are currently provided with the development platform. A software layer, referred to in this book as the Business Logic Foundation (BLF), will attempt to bridge this gap. The Java and J2EE platform continues to evolve and close the gap. However, it still remains even as a large number of people and organizations are working to add services to the platform. Due to the complexity of enterprise development, the widely varying set of requirements that dif-
ferent businesses and organizations have, and the many design considerations, it will take a significant amount of time for the standard to mature to the point where it ad- dresses all of these needs. In fact, even as the underlying platforms and standards evolve, technology and problem domains also grow, thus making it likely that closing the gap will resemble a calculus equation represented by a curve which slowly ap- proaches zero, but never actually gets there.
The automation capabilities within technical frameworks provide a high level of reusability across applications. Reusability is of course the “Holy Grail” of object- oriented software development. However, it has been very hard to achieve in many practical settings. Given a strategic application architecture and the set of guiding principles, you can position yourself to benefit from software reuse. The Enterprise JavaBean specification goes a long way toward having standard, reusable business components across applications. However, it is the role of the application architecture on top of J2EE to enable those components to be reused. It is important to have an ap- plication architecture that easily allows components to be plugged in to the rest of the system without adding significant overhead.
One way to plug in different components is through a messaging layer that buffers the different interfaces and systems. In complex architectures, this is the right solution, but for many applications, the overhead is too much of a price to pay. Two primary strategies to promote and enable the reuse of domain components are realized through the first two principles, design patterns and automated foundation components. One such example is that of the Service-Based Architecture layer that provides a standard interface for process-based components. By creating a standard interface that is used by the user presentation layer, a service such as Retrieve Account Data can be reused from different screens that require customer data. Services such as Account Deposit and Account Withdrawal can be reused as building blocks in an overall service, Trans- fer Funds. The fact that there is a service layer at all in the architecture allows the ser- vices themselves to be reused from different client devices. Finally, the standard interface of the service components allows you to automate their invocation through a configurable foundation layer within the reference architecture.
Use Metadata-Driven Components
Metadata is usually defined as data that describes other data. This book also uses the term “metadata” to refer to the many data elements that define the attributes and behaviors of various software components. Some examples of this could be the list of properties and their respective data types for a given business object, or it could be the form name and associated configuration information for a Web page. Much of the metadata that defines these components comes from design models described in UML.
The principle of using metadata to drive components again builds upon a previous principle, that of automating the tasks of software development. Metadata is used as an input to the “framework” services that automate and drive the behavior of J2EE components. This is applicable at all levels of the architecture. In the case of business objects, metadata can be used to define the business entities and their attributes. At the workflow or transaction level, metadata can be used to drive the process flow of complicated tasks. At the user interface level, it can define a particular Web page form
xviii J2EE Best Practices: Java Design Pattens, Automation, and Performance
and how it should be processed. All of these elements of applications can be abstracted and defined using metadata. The J2EE specifications themselves rely on different forms of metadata to configure and deploy components. A perfect example is the ab- stract approach taken by EJB 2.0 toward Container-Managed Persistence (CMP). The EJB deployment descriptors contain the metadata that maps the bean’s properties to database tables, as well as defining any relationships that the bean may have with other components.
Not every process or function should be defined using metadata (everything in moderation, as they say). There are some drawbacks to this approach that should be considered and that may not make it the right approach for every task. A metadata- driven abstraction usually will add some overhead to the execution of the task when compared to explicit lines of code used to do the same job. This overhead is typically negligible when compared to something like a single database I/O request. However, it should be considered nonetheless in the overall approach to software development, especially where transaction throughput is essential to the success of an application.
Another potential drawback of this approach is the fact that it can make reading and debugging code a bit more difficult. A separate file or repository that contains the metadata determines portions of the flow through the code. There are a number of ar- guments to counteract this point, some of which have been mentioned here already.
The primary argument is that these foundation components, which are configurable through metadata, become highly tested components that become almost like a black box to the rest of the application. Once you have these components working correctly, very little time is spent looking at the “framework” code. The behavior of an applica- tion can be determined simply by looking at the client code and the metadata inputs to the service. Consistent use of these foundation components rapidly makes this contention less of an issue. Another less structured argument is that well-written object-oriented code is difficult to sit down and read in the first place because the meth- ods are typically very small and you often have to jump back and forth from object to object anyway in order to decipher what is going on. This issue was dealt with on a different level when software development moved in large part from procedural code to object-oriented development. It is usually easier to read and understand a contigu- ous block of procedural code than it is object-oriented code, but the many benefits found in OO development far outweigh this minor and perhaps even debatable disad- vantage. Some of these same arguments apply to a metadata-driven approach as well.
As in many aspects of the J2EE architecture, both the pros and the cons must be weighed for a given design decision before making a choice. As is the case with so many architecture decisions you will see, the solution is often a middle-of-the-road choice in which metadata is used for key components that provide the maximum ben- efit. Elements of business applications that are data intensive and heavily used, such as forms processing and business object persistence, will use metadata to rapidly develop quality implementations.
The industry seems to be moving to storing many pieces of data in XML format, and metadata is no exception. Storing metadata as XML provides a number of benefits:
XML data provides a standard format that can be stored either in a file or in a database table.
Most design tools can generate XML data from their models; many tools now support XMI (XML Metadata Interchange), a standard XML format for object metadata.
XML can be created or modified using a number of different tools including XML editors, custom-written tools, or in many cases, even a simple text editor.
An interesting effect of using metadata is that it separates pieces of the application design from the code. This is helpful for a number of reasons:
A higher number of application functions driven by the design imply that fewer application changes will require actual code changes. This increases the speed of maintenance cycles and deployment.
XML supports a model-driven development approach; the design models become accurate pieces of documentation for the system and are used to generate application components or the metadata input to foundation components.
Much of the input to application code can originate from design models.
The object models for the business entities contain the properties and the relationships between the entities. This metadata can be exported from design tools into XML. The XMI specification provides one such format to do so, and design tools are starting to support it. If a configurable business object base class can manage the properties and relationships for a business object, you have now automated this portion of the business object through metadata input almost completely through the design process. Of course, specific business methods and other application components will also modify the properties of the business object and create instances of relationships, but the logic to do so has been automated through the metadata-driven process.
Practicality: Performance and Scalability
The last principle, essentially performance engineering, is one that underlies all else.
Avoiding this topic until the final phases of any project can have serious consequences.
The quickest thing (no pun intended!) that will keep people from using your system is poor performance, especially in today’s fast-paced Internet world. Business application users are accustomed to the performance of client-server applications over private net- works and consumers or Internet users are very impatient when it comes to waiting for a Web-site page to load. Thus, although it is true that computers are getting faster and more hardware is always an option (if you built a scalable solution), you must keep a watchful eye and build performance into the development process from the very beginning. It must be a part of the design process because it often involves trade-offs with other as- pects of a system, most often the flexibility that an application provides to the user.
Java, the language itself, can quickly approach the performance of C/C++ in many situations, a language widely regarded as a high-performance choice for even the most demanding applications. This is primarily due to the evolution of just-in-time (JIT) com- pilers that now aggressively translate Java byte code and perform code optimizations.
xx J2EE Best Practices: Java Design Pattens, Automation, and Performance
This is particularly true on the server side, where you typically have a large set of Java classes that will be executed many times. The initial overhead of performing the translation into native instructions is usually not worth mentioning, and thus in theory, the majority of the code should be comparable to compiled C++ code. One weakness that Java still has when compared to C++ is the garbage collection process, which adds some overhead. However, the programming benefits are well worth the minimal cost involved in terms of memory allocation and management, so this really does not even become an issue. In fact, as processor speeds continue to increase, the difference between the two languages themselves is likely to become almost insignificant. How- ever, component services provided by J2EE add another layer on top of the language, and you must look very closely at the impact that component services have on the application’s overall performance. While J2EE provides many valuable services, such as object persistence and naming and directory services, their benefits must be weighed against their costs.
Many solutions will involve using Enterprise Java services in cases in which they provide the most benefit, but not as a standard across the board. This is a common ten- dency of building J2EE architectures, to use the enterprise components across the board from front-to-back in the software architecture. A key example of this is the use of Entity Beans. Relatively speaking, Entity Beans are fairly heavyweight components, and thus should not be used to model every business object in an application, particu- larly if each business object maps to a row in the database. Doing this can quickly degrade the scalability, and thus the usability, of an application. A scalable architecture is a must for almost any system, and design guidelines discussed in this book for each layer of the architecture must be applied when deciding on the foundation for software components as well as in building the individual components themselves.
How This Book Is Organized
The structure of this book starts with a conceptual view of business applications and moves all the way to the realization of a corresponding application architecture and sample application. An introduction is first given to the reference architecture ap- proach and how it is applied to J2EE technology. The three basic layers of the reference architecture (business objects, services/processes, and user interaction) are each built from the ground up, starting with design concepts, moving to relevant J2EE best prac- tices, and ending with a J2EE implementation. Each layer is discussed as a general foundation for development in addition to its practical use in the form of a sample bank application that is constructed throughout the book. After having moved through the architecture vision, best practices, and implementation, the last set of chapters then take a step back and look deeper into topics such as application security, performance, and reuse.
Chapter 1, “Building Business Applications with J2EE,”introduces and discusses the common elements of business applications. The common characteristics are abstracted out as a foundation for an application architecture approach. The layers of the reference architecture are introduced, and the components within each layer are de- fined. The J2EE platform is briefly covered, and the reference architecture is mapped to its implementation as J2EE components. The Model-View-Controller architecture pat-
TE AM FL Y
Team-Fly
®tern, also commonly known as the Model 2 approach in Web development, is presented as an overarching aspect of both J2EE technology and the reference architecture.
Chapter 2, “The Business Object Architecture: Design Considerations,” covers design elements of the business object layer of the reference architecture. This chapter introduces the bank application’s object model as an example to study. The elements of business object components are discussed and the implementation options in J2EE are considered. Design elements discussed include stateful versus stateless, Entity Beans versus regular Java objects, persistence mechanisms, and transaction concurrency.
Chapter 3, “Building Business Objects: Managing Properties and Handling Errors,”walks through an implementation of the first half of business object responsibil- ities, which include property management, business validations, and handling error con- ditions. Due to the amount of functionality within business objects, their implementation is divided into chapters 3 and 4. An explicit implementation of the Account business ob- ject is discussed and then a generic property management approach is introduced. A metadata-driven base class implementation is described that can be used for all business objects. A standard interface for business objects is introduced so that all objects can be dealt with generically and consistently. Value objects and bulk accessor methods are also discussed. An error list mechanism is introduced and implemented that manages a set of configurable business errors for an object. General error and exception-handling tech- niques are discussed and applied to the business object implementation.
Chapter 4, “Building Business Objects: Persistence, Relationships, and the Template Method Pattern,”walks through an implementation of the second half of business responsibilities, which include persistence of the object’s data to a database, management of interactions with other objects, and the use of the Template Method pat- tern to build extensible, reusable business logic templates. Options for persistence that are discussed include the explicit use of JDBC, a metadata-driven JDBC framework, third-party and open-source persistence frameworks, and Entity Bean Container-Man- aged Persistence. Sample implementations are shown and discussed for each of the op- tions. The business object lifecycle is abstracted through the construction of a business object factory, and implementations are shown for JDBC, Entity Beans, and Castor, a popular open-source persistence framework for Java. Object collection services are also discussed as a faster alternative to using business objects for read-only operations, and best practices are provided for using JDBC if that alternative is chosen. Data caching and a JMS-based refresh mechanism are also addressed as an option to prevent unnec- essary database I/O. The responsibilities of aggregated business objects are discussed and corresponding methods are added to the standard business object interface. The Template Method pattern, which enables a key concept of the reference architecture, au- tomation with extensibility, is discussed. Implementations of a save template, an object creation template, and an aggregated object template are constructed to automate basic business object functionality. The overall metadata DTD and implementation are then discussed. At the end of this chapter, readers will have a set of design concepts and code that can be used to quickly build robust business object components.
Chapter 5, “The Service-Based Architecture: Design Considerations,” covers design elements and the rationale behind the service component layer of the reference architecture. The basic elements of these process-oriented objects are discussed, and implementation options are considered. Services are categorized as either update or data retrieval. The concept of the Session Bean as a component wrapper to regular
xxii J2EE Best Practices: Java Design Pattens, Automation, and Performance
Java implementation classes is introduced. The majority of the chapter then covers the interface of the service components, the benefits of choosing a standard interface, and the considerations for different data structures such as XML, value objects, and argument lists.
Chapter 6, “Building Service-Based Components,”walks you through the imple- mentation of service components in the reference architecture. Examples are given for both explicit interfaces and a standard interface. A service data class is created that en- capsulates value objects, argument lists, and error data in order to create a standard service interface. The implementation of an EJB wrapper around a regular Java class implementation is constructed. A service component base class is introduced for stan- dard error handling, transaction management, and the invocation of the implementa- tion classes. The general responsibilities of both data retrieval and update services are discussed. Some service implementations from the bank application are constructed such as TransferFunds, ChangeAddress, and GetAccountList. Strategies for building generic reusable services, invoking services within other services, and using the con- troller pattern are also discussed.
Chapter 7, “The User Interaction Architecture: Design Considerations and an Overview of Jakarta Struts,”covers design elements and the common aspects of the user interaction layer of the reference architecture. The key aspects of web-based user interaction are abstracted as events, actions, services, and Web pages. These abstrac- tions and the design considerations are used so that the core responsibilities of the con- troller architecture can be broken down into eight steps. These steps are automated to the extent possible and partitioned effectively between the controller and the action classes. Design considerations for state management are discussed with a brief overview of scope within the JSP/servlet architecture. Best practices for applying the Model-View-Controller architecture to J2EE are discussed including managing the ses- sion size, and JSP templates and encapsulating presentation logic in reusable custom tags. The last part of this chapter provides an overview of the Jakarta Struts project, an open-source implementation of the Model 2 architecture. The controller architecture of Struts is discussed, but the real power is shown to be within the JSP tag library that eas- ily integrates request-handling functionality into dynamic Web pages.
Chapter 8, “Building the User Interaction Architecture,”walks through the imple- mentation of the user interaction layer using Struts. Implementation aspects are dis- cussed and illustrated through practical examples of constructing the bank’s Web site.
The change address and view accounts pages are constructed as examples of simple update and data retrieval functions. The new customer wizard is constructed as an example of a multipage form. Strategies for the implementation of the user interaction components are discussed. Options are shown for implementing the event object and service data objects both independently and separately. Integrating error handling from front to back in the reference architecture is discussed and implemented. Some custom tags are created to illustrate the power of reusable presentation logic that inte- grates with the reference architecture, such as the drop-down tag, which automatically gets its data from a specified object cache. The implementation of the JSP template mechanism, as used by the bank’s pages, is defined and discussed. The creation of extensible base action classes for standard logic is discussed and implemented. At the end of this chapter, readers have a complete set of tools and design concepts to rapidly build transactional Web sites using J2EE technology and a Business Logic Foundation.
Chapter 9, “Strengthening the Bank Application: Adding Security and Advanced Functionality,”gives a brief overview of application security in J2EE and its use in the bank application. Some of the more interesting design aspects of Web-based applica- tions are discussed through advanced pages within the bank application. A set of ad- ministrative pages that introduce implementation strategies for multiple submit buttons on a form and multiple objects being updated on the same form are developed.
Chapter 10, “Performance,”presents an approach to performance engineering that balances the focus throughout the software development lifecycle. An emphasis is placed on scalable architectures and benchmark testing up front to determine the validity of proposed solutions. Strategies for measuring and optimizing performance are discussed including object instantiation, object caching, and the use of J2EE com- ponents such as Entity Beans.
Chapter 11, “Moving toward Reuse in the Reference Architecture,”focuses on common roadblocks to reuse and best practices that can be used to offset these hurdles.
Roadblocks range from the social aspects all the way to technical limitations. Both J2EE and the reference architecture are positioned as key aspects of a reuse architecture based on configuration and extensibility, the use of standard interfaces, and a layered modular architecture. Reuse and adaptability are considered in a strategic view of the reference architecture.
Who Should Read This Book
This book is intended for those who have already had some exposure to J2EE tech- nologies such as EJB and JSP/servlets, although architects and software engineers of all skill levels will find the design considerations, implementation techniques, and reusable code useful. Technically astute managers and other information technology professionals will also find many sections of the book, such as the chapters on security, performance engineering, and reuse and strategic architecture, helpful.
This material will be of interest to any Java technologist building business applica- tions using J2EE because it provides concepts and examples of how to build applica- tions faster and with greater quality. Many J2EE books on the market provide basic API examples but do not go into detail about the design implications of different J2EE ar- chitectures or how to automate the development of J2EE components. This book does those things on both a theoretical and practical level.
Tools You Will Need
To run the sample application and use the business logic foundation software, you will need the following:
Any J2EE 1.3–compliant application server such as BEA Weblogic 6.1 Jakarta Struts v1.0 or greater, which is available at
http://jakarta.apache.org/struts
(Optional) The Castor Data Binding Framework, part of the ExoLab project, which is available at http://castor.exolab.org/
What’s on the Web Site
The companion Web site contains all of the code from the Business Logic Foundation that is discussed as part of the reference architecture. It also contains the code for the sample bank application. You will also find links to relevant Web sites, open-source projects, and industry information on:
J2EE and J2EE Blueprints The Jakarta Struts project The Jakarta Commons project The Castor project
Performance testing
Summary
The concepts and principles that are discussed here provide a foundation for a set of best practices that will be used effectively to build Internet applications using J2EE technology. These design and development guidelines feed into the creation of a pow- erful architecture that is used to develop Internet applications faster and with greater performance, quality, and reusability. J2EE provides a powerful standard upon which you can build components and applications; with the right set of development prac- tices and software assets, Web-based business application development moves closer to a process known as software fabrication, in which applications are built using pre- fabricated components and frameworks.
xxiv J2EE Best Practices: Java Design Pattens, Automation, and Performance
1 1
Building Business Applications with J2EE
1
The approach to developing Web applications with J2EE (Java 2 Enterprise Edition) is based on a number of factors, which include:
The common elements of business applications
The vision of the software architecture; that is, the definition of the components and their interaction
The J2EE technology platform used to implement the software
Business applications share a number of common elements because they are all used to implement business processes and manage the information of a business. Conse- quently, business entities and processes can be modeled as software components. In today’s world, users access many business applications and their underlying compo- nents through the Internet, usually by using a Web browser but increasingly through wireless and other Internet devices. The vision of the software architecture should in- tegrate the common elements into a component structure that models the business today and positions it for the future. On the technical side, the architecture should po- sition the development organization to meet the requirements of flexibility, perfor- mance, and time-to-market constraints. The execution of the software architecture vision is driven by the guiding principles discussed in the introduction and a number of J2EE best practices described in this book.
2 J2EE Best Practices: Java Design Patterns, Automation, and Performance
This chapter defines a set of fundamental elements that are common among Web- based business applications. This set of key elements drives the definition of a refer- ence architecture that comprises three layers: business objects, process-oriented or service-based objects, and user interaction components. The basic theory behind the J2EE platform approach is briefly discussed and followed by an introduction to a cen- tral design pattern that is predominantly used to implement J2EE applications, the Model-View-Controller (MVC) architecture pattern.
Elements of Transactional, Web-Based Business Applications
Business applications, especially Web-based transactional applications, share many common characteristics. It is important to take a step back and look at these character- istics because they form the basis of many application architectures. In fact, these elements are the model on which the software architecture is based. From these char- acteristics, you derive the different types of application components and services that are required. The architectures discussed in the remainder of this book are based on these elements. These elements map to software layers and components, and a thor- ough analysis of how the mapping should be done is given in the following chapters.
In short, these elements provide the foundation of the architecture, and they drive the software layers that enable flexibility and reusability.
Business Entities
Businesses deal with different entities all of the time. These range from higher-level entities such as a customer or a supplier down to lower levels such as purchase orders or even perhaps individual line items on a contract. These entities share a number of common characteristics:
Behaviors Properties
Relationships with other entities Rules or policies
An example used throughout the book is a bank. Two primary entities that banks deal with are customers and accounts. Accounts have properties, such as a current bal- ance and minimum allowed balance, as well as rules that enforce policies of what hap- pens when the current balance falls below the minimum. Accounts also have behaviors such as deposit and withdrawal, and they interact with customers, the other entity in the bank example.
Entities become participants in business processes. They often have different sets of business policies or rules that must be enforced. An application will likely be interested in the persistence of the state of the entities, for example, the status of a purchase order or the current balance of a bank account.
Business entities are of course the foundation of object-oriented design and devel- opment. While this book is not meant to be a discussion of object-oriented theory, it is important to take note of these primary characteristics to motivate further discussion on their place in the software architecture and on how a technical solution can address this element of business applications.
Business Processes
Businesses use many processes to carry out the work of their business. These processes often have some sort of specified workflow and often involve one or more business en- tities. They must be executed in a secure manner, and they involve units of work that cannot be broken apart. One example that illustrates both points is the process of trans- ferring money from a checking account to a money market account. The bank provid- ing the service does not want the deposit credited without also accounting for the withdrawal, or it loses money.
The accessibility of these business processes, or services, is becoming ever more of an issue. In the example, a bank’s customer may want the ability to transfer the funds from a home PC through a browser or from a wireless device while on the road. Busi- nesses exchange funds all of the time, and a Web service for a transfer of funds through a secure, B2B (business-to-business) Internet client provides another potential access point.
Based on the bank example, business processes share the following characteristics:
Include some flow of activities
Involve business entities as participants Need to be executed in a secure manner
Comprise units of work essential to the business Need to be accessible from different clients:
Browser-based applications Wireless devices
B2B Web services Other Internet clients
User Interaction
Many business processes would not be very helpful or effective if end users could not access them. As described in the previous section, the types of access points are grow- ing, and the requirements can vary widely based on how the information or service should be presented to each access device.
The user interaction portions of applications typically share the following charac- teristics:
Application presentation, such as HTML or XML over HTTP Access to business functions and services
4 J2EE Best Practices: Java Design Patterns, Automation, and Performance
Static and dynamic content Screen flow, or page navigation Forms processing
Error handling
The sample bank Web site exhibits these characteristics. There are both static content (account holder policies) and dynamic content (list of customer accounts and detailed information about each). In order to transfer funds between accounts, the user must fill out a quick form to select the amount and the from and to accounts. Any data entry mistakes, such as entering an amount greater than the balance, must be handled ac- cordingly and the user must be given the opportunity to retry the transaction.
A bank customer accessing this service from a handheld wireless device would en- counter all of the same elements. The application itself would need to tailor the content to fit onto the smaller screen and communicate using WML instead of HTML, but the same issues exist.
A Web service that can be used by a B2B partner to transfer funds would share many of the same characteristics except for the content-generation and screen-navigation elements, but all of the forms-processing and error-handling logic would still be needed. A Web service is actually a simpler example than the first two, although it does introduce its own set of challenges. For the most part, the user interaction layer in the case of a Web service is an HTTP wrapper around the business process.
The Reference Architecture
The primary elements of business applications naturally fit into layers, starting with the business entities themselves. They are at the core of what the business deals with every day. Every business has processes or transactions that involve these entities.
Finally, these processes and transactions need to be accessible to users or business partners. Figure 1.1 shows how these layers fit together in a reference architecture.
Once you move toward technical solutions to implement these layers, you will see that your software architecture diagrams closely resemble this diagram.
The software architecture models the three primary elements of business applica- tions and provides technical implementations for each of them. Each of these cate- gories is a conceptual layer in the architecture: business entities, business processes, and user interaction. This book defines a set of terms to describe these software layers in relation to the reference architecture. Note that these are not standard J2EE terms, simply a shorthand notation used to communicate the vision of the application archi- tecture and describe how the components fit together.
Business Object Architecture. The business entities become the core of the
“Business Object Architecture.” This term is used to describe the layer of business object components that model these entities and interact with enterprise information systems. This typically involves some combination of N OT E
Figure 1.1 The Structure of a Business Application.
Web Browser
Wireless Device
B2B Web Service
Client Thick-Client
Application Transfer
Funds
Purchase Product
Account
Product
Customer User
Interaction Business
Processes Business
Entities
Change Address 123 Main.
St.
regular Java classes and Entity Beans in J2EE architectures. Business entities within the bank example include a Customer and an Account.
Service-Based Architecture. The business processes become a part of the
“Service-Based Architecture.” This term is used to describe the layer of the business components that implement the processes and workflows of the business. The typical incarnation of a “service” in this reference architecture is a stateless Session Bean, although your definition is not limited to this. In this book, “service” describes a process-oriented object as opposed to an object that models a particular business entity. A Session Bean can act simply as a component wrapper to one of your process-oriented objects, although these objects could be invoked directly from another service or business component as well. Business processes within the bank example include TransferFunds and ChangeAddress.
User Interaction Architecture. The user interface and client interaction aspects are simply called the “User Interaction Architecture.” In a J2EE architecture, this is typically implemented under the Model 2 approach, which uses servlets and JavaServer Pages (JSP) to implement a Model-View-Controller (MVC) Web architecture. User interaction within the bank example includes Web pages with which the user can transfer funds and change their address.
As described in this book, these layers define interaction points in the software archi- tecture. Note that at this point you should not consider network or hardware
6 J2EE Best Practices: Java Design Patterns, Automation, and Performance
Figure 1.2 The Basic Architecture Layers Diagram.
Web Browser
Wireless Device
B2B Web Service
Client Thick-Client
Application
Enterprise Application Application Databases User Interaction
Architecture
Service-Based Architecture
Business Object Architecture
architecture. These software layers could reside on the same physical tier or be distrib- uted across a network. For now, this is somewhat irrelevant. The interaction of the soft- ware components and the partitioning of functionality is the key point to be drawn from this view of the architecture.
Figure 1.2 illustrates the software architecture diagram, which closely resembles the diagram that represents the flow of business application characteristics.
Business Object Architecture
The Business Object Architecture contains the components that implement the busi- ness entities in the system. Each of these components manages the data and business logic associated with a particular business entity. This includes the persistence of that object’s data, typically to a relational database. This database access can be imple- mented by the container in the case of CMP (Container-Managed Persistence) Entity Beans or by the developer in the case of BMP (Bean-Managed Persistence) Entity Beans or regular Java classes. In the last two cases, in which the developer does the work, it is a best practice to isolate the database access into a separate data-access layer. If there is any data access outside of the business object model, this should also be included in this layer. This includes database queries that are run in order to retrieve read-only data for presentation to the user.
In the bank application, a business object could represent entities such as a customer, a bank account, or even an individual transaction on the bank account such as a with- drawal. These business objects can be implemented either as Java classes, Entity Beans, or some combination of the two. The persistence of each business object is abstracted
TE AM FL Y
Team-Fly
®out to the extent possible so that separate data objects, persistence frameworks, or Container-Managed Persistence services can be used to have the object data persist in the database.
Service-Based Architecture
The Service-Based Architecture contains the components that implement the business processes and transactions of an application. These typically are process-oriented objects that represent units of work or implement a business workflow. Many of the service components are relatively small in content because the business objects are used to do much of the work. Other services are quite complicated in nature. Not all software architectures include a service-based layer; however, it can add tremendous value in terms of flexibility, reusability, and component design. The concept of services allows the front end to be decoupled from the back-end business object components.
Service objects are used to coordinate transactions that involve multiple business com- ponents and provide a simple interface to the user interaction layer. Services them- selves become reusable across screens, applications, and different client access points.
As you will see, a simple stateless Session Bean wrapper around a service object allows you to easily distribute the service and manage the transaction as well, one of the great- est benefits of the EJB (Enterprise JavaBeans) architecture.
One important aspect of the Service-Based Architecture is that services typically fall into one of two categories: read-only and update. Remember that in the architecture diagram, all the back-end functionality that is required to create the presentation layer needs to be provided by a service. Thus, many services within the application archi- tecture will be data retrieval services.
Depending on the technical architecture, the presentation layer may or may not be able to contact the data-access layer directly. Some configurations will separate the user interaction layer (Web container) and the Business Object Archi- tecture (EJB container) onto different physical tiers with no direct path from the user interaction layer to the database. Other architectures combine the two layers on one physical tier. Thus, for maximum efficiency, you would not need a service to retrieve a result set. This issue is hotly contested in the industry, and will be covered later in the chapters on User Interaction and Service-Based Architecture.
In the bank application, the business processes include allowing customers access to their account information, transferring funds between accounts, and changing the cus- tomer address. These services are implemented as process-oriented objects and then wrapped with stateless Session Beans to implement the service component pattern dis- cussed in the introduction. They are initially deployed as remote EJB components so that the services can be potentially accessed from a number of different clients. How- ever, a deployment with local interfaces would work equally well in cases where the Web tier and EJB tiers are colocated on the same physical machine. The J2EE platform section later in this chapter discusses the different tiers and the nature of the respective J2EE components in more detail.
N OT E
8 J2EE Best Practices: Java Design Patterns, Automation, and Performance
User Interaction Architecture
The User Interaction Architecture contains components that process user requests, in- voke application services, and generate responses sent back to the user. In a Web-based application, this layer would process HTML form submissions, manage state within a user session, generate Web-page content, and control navigation between pages. It is easy to see that the user interaction layer has a large number of responsibilities. Thus, it is not surprising that the User Interaction Architecture has more types of components than the other two layers combined. Whereas there are only service components in the Service-Based Architecture and only data and business objects in the Business Object Architecture, the User Interaction Architecture contains page components, request- processing components, state management, tag libraries, and user action components just to name a few. And that doesn’t count content generation, personalization, portals, and other complexities that factor into many business applications.
The point is that this layer encompasses a lot of functions. The good news is, how- ever, that many of the functions within this layer can be automated through config- urable foundation components. Web design will always require people skilled in graphics design and human factors, but integrating business functionality into Web pages can be done in a flexible, robust manner through the Model 2 paradigm, the MVC (Journal of Object-Oriented Programming 1988) architecture pattern applied to the J2EE Web tier architecture. Both Java Swing and the J2EE Blueprints (Kassem and the Enterprise Team 2000) sample applications are based on this architecture pattern. A major portion of the reference architecture discussed in this book is a generic, config- urable implementation of the Model 2 architecture. This allows you to automate the processing of user requests and page navigation, a major portion of the responsibilities within the User Interaction Architecture. Reusable libraries can be used for many of the other functions, such as tag libraries and style sheets for the purpose of content generation.
For each layer of the architecture and each element of the business application within these layers, design choices will be considered that impact the overall goals of the system, such as performance and flexibility. The four guiding principles discussed in the introduction will be applied to each element in order to use proven design pat- terns and automate as much of the processing as possible. The Business Logic Founda- tion will cut across these different elements to provide configurable, metadata-driven components to automate the work.
The User Interaction Architecture encompasses any application components resi- dent on the client device as well. In the case of client-server applications, this would include the entire thick-client, Java Swing GUI (graphical user interface) application.
However, in the case of thin-client Web applications, this is typically limited to some amount of JavaScript that runs within the browser. The JavaScript code comes from the Web server, although it is actually run on the client side. Java applets are an additional possibility, although they are not often used in enterprise Web development. Thus, the majority of the user interaction processing for Web applications is handled on the server.
In the bank application, user interaction is primarily through a set of pages for the bank’s Web site, which provides customers with access to accounts and Internet bank- ing functions. There is also a set of Web pages for bank administrators to facilitate