About the Book

This book is for every Java web developer, regardless of his or her level of expertise. It is designed primarily for intermediate to advanced developers, who understand the specifics of the various web APIs in Java but haven’t yet mastered the best way to apply them. It is perfect for developers who have heard terms like Model-View-Controller and Model 2, but weren’t present for the series of events that led to the widespread adoption of these best practices. It is also perfect for designers and architects of web applications because it discusses the implications of architecture and design at every opportunity.

This book is also well suited to developers who have looked at (and possibly struggled with) one of the many web frameworks on the market. It is unique in its coverage of web frameworks, giving equal weight to six different frameworks and comparing them on equal ground. Whether you are planning to use a framework or you want to write your own, understanding the similarities and differences between the existing frameworks will save you a great deal of time. Art of Java Web Development also illustrates new possibilities for those who are using a framework but aren’t happy with it.

In addition, this book is aimed at developers who must create applications in the real world. Many of the best practices books treat each tip as the sole focus of a chapter, with no discussion of integrating it into a real application. Real applications are messy, requiring lots of moving parts working together seamlessly. The best practices in this book are presented in the context of a working e-commerce application, with all the places that the real world intersects with the academia of the pattern discussed.

How this book is organized

Art of Java Web Development consists of three parts. It begins with coverage of the history of the architecture of web applications, highlighting the uses of the standard web API to create applications with increasingly sophisticated architectures. The discussion leads to the development of industry-accepted best practices for architecture. Instead of simply pronouncing one architecture as the best, Art of Java Web Development shows the history and evolution of each architecture.

The second part of the book provides a unique overview of the most popular web application frameworks. Trying to evaluate a framework is difficult because its documentation typically stresses its advantages but hides its deficiencies. This book builds the same application in six different frameworks, encouraging you to perform an “apples to apples” comparison. The last chapter of part 2 provides a candid evaluation of the pros and cons of each framework to assist you in making a decision or in evaluating a framework on your own.

The selection of the correct framework is only the beginning of the life cycle of an application. Part 3 examines best practices, including sophisticated user interface techniques, intelligent caching and resource management, performance tuning, debugging, testing, and web services.

Part 1

Chapter 1 serves as the jumping-off point for the book. It highlights all the topics to come in the subsequent chapters and explains my primary motivation for writing the book.

Chapter 2 begins our discussion of the evolution of web applications. The idea behind this chapter is to present an application built by a developer who is very good with Java and understands the web APIs but hasn’t yet applied best practices and architecture. The first pass at the application uses only servlets (which was the only tool available when the web APIs first debuted). Then we build the same application using just JSP. In both cases, we highlight the strengths and weaknesses of the resulting applications.

Chapter 3 carries the evolution a step further with custom tags. It takes the JSP application built in the second chapter and improves it using custom JSP tags.

Chapter 4 represents the culmination of the evolution of architecture and design. Here, we rewrite our sample application as a Model 2 application. You’ll also learn how to leverage design patterns to improve the Model 2 application.

Part 2

Part 2 covers six web frameworks. In chapter 5, you’ll learn about Struts. We introduce this framework in chapter 1, but here we “deconstruct” it and describe all the important moving parts. Chapter 6 examines Tapestry, another Model 2–based open-source framework. We show you how the Tapestry API completely encapsulates the web APIs in Java. Chapter 7 takes a look at WebWork, another open-source Model 2 framework. It includes some innovative ideas for passing just-in-time information between the layers of Model 2.

Chapter 8 covers the only commercial framework in the book, InternetBeans Express, which is the framework included with Borland’s JBuilder. It is a rapid application development environment that lets you create web applications in record time.

Chapter 9 examines Velocity, which can act as a replacement for JSP and other visual representation languages. Velocity is a popular open-source framework that is very cohesive and single-purpose. In chapter 10, you’ll learn about Cocoon, an open-source publishing framework that also includes capabilities as a Model 2 web framework.

Chapter 11 offers an evaluation of all six frameworks. It lays out the criteria we used to judge them, and gives you the information you need to evaluate frameworks on your own.

Part 3

Part 3 looks at best practices and helpful techniques for building web applications in the real world. The topic coverage is very broad, but we focus on various techniques and tools for building web applications.

Chapter 12 discusses techniques for separating concerns between the tiers of the application. Chapter 13 describes user interface techniques for managing the flow of information in web applications. It shows you how to build page-at-a-time displays and sortable columns without sacrificing clean Model 2 architecture. We also discuss building “undo” operations in web applications, using either transaction processing or the Memento design pattern. Chapter 14 focuses on performance. You’ll learn how to profile web applications to determine whether performance bottlenecks exist, using both SDK-supplied and commercial tools. Next, we look at performance pitfalls and common mistakes and offer solutions. Then we delve into object pooling and explain how to implement it using either Java references or Jakarta Commons pooling.

Chapter 15 complements the previous chapter by showing you how to conserve resources. We examine several sophisticated caching techniques using both the Flyweight and Façade design patterns. In this chapter, we build caching into the sample eMotherEarth application.

Chapter 16 moves away from specific design techniques and focuses on debugging and logging. You’ll learn how to debug web applications using nothing but the tools supplied with the SDK (i.e., the command-line debugger). We also show you how to use commercial and open-source debuggers, including JBuilder and NetBeans. The last part of the chapter examines the Java 1.4 SDK logging package and log4j, a popular open-source logging package.

In chapter 17, you’ll learn about unit testing, an often-neglected part of application development, especially in web applications. We show you how to build tests for your web applications and discuss JUnit and JWebUnit, both very popular open-source testing frameworks.

Chapter 18 wraps up the best practices portion of the book by examining web services and explaining how to incorporate them into your existing web applications. Finally, chapter 19 highlights some important topics that are simply beyond the scope of this book. The bibliography at the end of this book includes references to the books cited throughout the chapters.

Notes about the samples

Art of Java Web Development contains many samples, mostly based around two main web applications. The samples also embody some of my ideas about the structure of source code. The samples illustrate the techniques covered in the chapter, but the coding technique may look a little unusual if you aren’t used to the style. However, once you see my rationale for writing code like this, you may well adopt it yourself.

The samples

Two primary samples appear throughout the chapters. The use of only two samples is intentional, but the reasons are different for each instance. The samples are designed to illustrate the topics in the chapters, including the architecture, design, and specific techniques.

The eMotherEarth.com sample

The architecture and technique samples revolve around the fictitious eMotherEarth e-commerce site. This site sells earth products, like dirt, leaves, mountains.... Fortunately, we don’t have to worry about delivering the products; we’re just presenting a catalog. The application is a simple four-page web application that allows logon, catalog display, checkout, and confirmation. Even though it’s small, this site is sufficient for us to highlight navigation, techniques, and architecture.

We use the eMotherEarth application in the early chapters to illustrate the architecture of web applications and how it has evolved from servlets, to JSP and custom tags, to the currently accepted industry standards. In later chapters, we use the same sample application to illustrate various techniques for creating user interfaces, implementing caching, managing resources, and other advanced topics.

The schedule sample

The other primary sample in Art of Java Web Development is the schedule application. It is a simple two-page application that manages scheduling information, and it appears in all the framework chapters. One of the goals of our book is to show the various web frameworks in a manner that permits direct, head-to-head comparison of features. Evaluating the frameworks based on their samples and documentation doesn’t allow you to perform this “apples to apples” comparison because there is no ANSI standard web application sample.

The framework chapters all build the same schedule application, each using the framework discussed in that chapter. Unless otherwise noted, all the samples use the same infrastructure for database access and representation of entities. The difference in each case is the framework itself. It is remarkable how different the versions of this sample end up, given the similarities of the basic architecture of most of the frameworks and the common elements used to build them. However, as you will see, the framework makes a tremendous difference in the implementation of a web application.

Sample setup

Art of Java Web Development is an intermediate to advanced book on web frameworks and best practices. As such, we do not cover the basics of setting up a development environment for the samples. You must handle that yourself. However, it is exhaustively covered in other books and on the Internet. Two infrastructure pieces are needed for the samples: a database server and a servlet engine. Each sample does include an Ant file to build the sample using the Ant build utility. Ant is available at ant.apache.org and is covered extensively in Manning’s book Java Development with Ant, by Erik Hatcher and Steve Loughran.

The database

Virtually all the samples in this book connect to a database because most real-world applications also have to retrieve data from a database. We use the MySQL database (available at www.mysql.com) because it is open source (and therefore free for developer use) and because it is a great database server. However, you aren’t forced to use it to run the samples. With each of the samples, we include a generic SQL setup script that builds the database for the application. The setup script is designed around MySQL but can be easily modified to work in any ANSI standard database server. To run the samples with MySQL, you must download it and set it up yourself. You’ll find a hyperlink on the book’s web site (www.manning.com/ford) that leads you to the MySQL site.

The servlet engine

The web applications in this book utilize standard Java web development code, so they all run in any Java 2 Enterprise Edition (J2EE)-compliant servlet engine. Unless otherwise noted, we generally use Tomcat for the samples because it is open source and is the reference implementation of the servlet API. Because the samples are J2EE compliant, they will run in any servlet engine.

The exceptions to the previous rule of thumb are applications that illustrate particular J2EE features not found in Tomcat. For example, chapter 12 features Enterprise JavaBeans and uses the JBoss application server instead of Tomcat. In any case, the samples all run in any servlet engine or application server that matches the standard J2EE architecture.

The frameworks

Part 2 of Art of Java Web Development covers various web development frameworks. These chapters include links where you can download the framework. We also include links to the frameworks on the book’s web site (www.manning.com/ford). Because of the nature of open-source frameworks and the Internet in general, it is possible that the frameworks will have moved. For example, during the development of the book, the Tapestry framework moved from SourceForge to Jakarta. Don’t be discouraged if you can’t find the framework using the link provided in the chapter. Most of the frameworks featured in this book are well established, meaning that they shouldn’t go away anytime soon. If you can’t find a framework, either search using your favorite search engine or go to the book’s resources web pages (www.dswgroup.com/art and www.nealford.com/art), which will have updated links.

The code structure

As you read the code in this book, you will notice some unusual characteristics about the structure of the code itself. For the structure of the code, I rely on a combination of the Template Method and Composed Method design patterns. The first is from the classic Design Patterns: Elements of Reusable Object-oriented Software by Gamma, Helm, Johnson, and Vlissides, (the “Gang of Four”), and the second appears in Kent Beck’s Smalltalk Best Practice Patterns.

The Template Method design pattern mandates extremely small, cohesive methods so that common behavior may be pushed up higher in the class hierarchy. It encourages extremely granular, single-purpose methods that perform only one task. The Composed Method design pattern encourages the same structure with extremely cohesive methods, but also adds the characteristic of very readable method names.

The problem we attack with these patterns is the tendency for embedded comments (i.e., the comments inside the method definition) to “lie.” They don’t mean to lie—and they generally don’t when first written. However, over time as the code changes, the comments fail to stay in sync. The solution to the less-than-truthful comments is to get rid of them. The method names themselves should indicate what the method does without the need for comments. Note that I’m not referring to method- and class-level comments (captured with JavaDoc). Those comments should remain in your code. The embedded comments should go.

To help enforce this coding style, we have a rule of thumb at our office that no method exceed 20 lines of code. If it is longer than that, it should be refactored into smaller, more cohesive (i.e., more composed) methods. Once you have this level of granularity, it is much easier to identify the methods that should move up in the class hierarchy (because they are generic) and apply the Template Method design pattern.

Using these coding techniques, the public methods of your class read like outlines of the intended actions of the method, which are in turn the private methods that perform the actual work. If the method names are clear enough, embedded comments (the ones that lie) aren’t needed—the code “speaks” to you. For example, here is the doPost() method from one of the more complex samples:



public void doPost(HttpServletRequest request,

                   HttpServletResponse response) throws

        ServletException, IOException {
HttpSession session = request.getSession(true); ensureThatUserIsInSession(request, session); ProductDb productDb = getProductBoundary(session); int start = getStartingPage(request); int recsPerPage = Integer.parseInt( getServletConfig().getInitParameter("recsPerPage")); int totalPagesToShow = calculateNumberOfPagesToShow( productDb.getProductList().size(), recsPerPage); String[] pageList = buildListOfPagesToShow(recsPerPage, totalPagesToShow); List outputList = productDb.getProductListSlice( start, recsPerPage); sortPagesForDisplay(request, productDb, outputList); bundleInformationForView(request, start, pageList, outputList); forwardToView(request, response); }

The intent of the doPost() method relies on the internal composed method names, each of which performs one atomic unit of work. If this method isn’t working, it is a fault in one of the private methods, which are each small and thus easy to trace into.

All the code in our book uses this coding technique. I have used it for years, and I firmly believe that it leads to higher quality code. With the tools available in the Java world for refactoring, it is easier than ever to either create code like this or modify existing code to take advantage of this technique.

The other semi-controversial coding artifact seen in my code is the absence of unnecessary braces, particularly around decisions and loops. While this is a common defensive coding technique, I find that I don’t like to code defensively. If you understand how the language works, defensive coding isn’t necessary. However, I understand that many of my colleagues really like the extra braces. If you have trouble reading code that doesn’t contain the extraneous braces, I recommend that you download the code and apply one of the source code beautifiers (like Jalopy, at sourceforge.net/projects/jalopy/) to "fix" the code.

Source code

All the code generated for Art of Java Web Development is available online, either at www.manning.com/ford or from my web site, www.nealford.com. My site has a page devoted specifically to this book at www.nealford.com/art. There is also a link to the samples on my company’s site, www.dswgroup.com/art.

Typographic conventions

Italic typeface is used to introduce new terms.

Courier typeface is used to denote code samples as well as program elements.

Author Online

The purchase of Art of Java Web Development includes free access to a private web forum run by Manning Publications, where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser to www.manning.com/ford. This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct on the forum.

Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the AO remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray!

The Author Online forum and the archives of previous discussions will be accessible from the publisher’s web site as long as the book is in print.

About the author

Neal Ford is the chief technology officer at The DSW Group Ltd. in Atlanta, GA. He is an architect, designer, and developer of applications, instructional materials, magazine articles, and video presentations. Neal is also the author of Developing with Delphi: Object-Oriented Techniques (Prentice Hall PTR, 1996) and JBuilder 3 Unleashed (SAMS Publishing, 1999). His language proficiencies include Java, C#/.NET, Ruby, Object Pascal, C++, and C. Neal’s primary consulting focus is the building of large-scale enterprise applications. He has taught on-site classes nationally and internationally to all phases of the military and many Fortune 500 companies. He is also an internationally acclaimed speaker, having spoken at numerous developers’ conferences worldwide.

Neal is also an avid (but slow) Ironman triathlete, competing in several races a year of varying distance. He is also a voracious reader, loves to listen to very eclectic music, watch high-quality movies, travel to exotic locales, and eat at fine restaurants (sometimes enjoying combinations of the above). He has also been known to sit in front of a computer for vast amounts of time. When at home, Neal enjoys the company of his wife, Candy, and two cats, Winston and Parker.