Part 1 covers the evolution of the architecture and design of state-of-the-art web applications.. Chapter 2 covers the evolution of web development in Java; chapter 3 explores that evolu
Trang 1ABOUT THE BOOK xxix
Manning’s commitment to our readers is to provide a venue where a mean-ingful 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 AOremains 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
materi-als, magazine articles, and video presentations Neal is also the author of
Develop-ing 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 eclec-tic music, watch high-quality movies, travel to exoeclec-tic locales, and eat at fine restau-rants (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
Trang 2The figure on the cover of Art of Java Web Development is a "Nukahiviens avec un
Tat-ouage Tout Different," a resident of Nukahiva Island in the Marquesas in French Polynesia Marquesans were known for their elaborate tatoos which, over a life-time, would cover almost all of their bodies Marquesan craftsmen also developed great skill in carving and decorating wood, stone and bone, and developed a rich repertory of surface designs and patterns, some of a type to be found throughout Polynesia, others distinctively Marquesan in origin and concept
The illustration is taken from a French travel book, Encyclopedie des Voyages by
J G St Saveur, published in 1796 Travel for pleasure was a relatively new phe-nomenon at the time and travel guides such as this one were popular, introduc-ing both the tourist as well as the armchair traveler to the inhabitants of other regions of France and abroad
The diversity of the drawings in the Encyclopedie des Voyages speaks vividly of the
uniqueness and individuality of the world’s towns and provinces just 200 years ago This was a time when the dress codes of two regions separated by a few dozen miles identified people uniquely as belonging to one or the other The travel guide brings to life a sense of isolation and distance of that period and of every other historic period except our own hyperkinetic present
Dress codes have changed since then and the diversity by region, so rich at the time, has faded away It is now often hard to tell the inhabitant of one continent from another Perhaps, trying to view it optimistically, we have traded a cultural and visual diversity for a more varied personal life Or a more varied and interest-ing intellectual and technical life
We at Manning celebrate the inventiveness, the initiative, and the fun of the computer business with book covers based on the rich diversity of regional life two centuries ago brought back to life by the pictures from this travel guide
Trang 3Part I
The evolution
of web architecture
and design
Look at the computer sitting in front of you, and you see the culmina-tion of architecture and design going all the way back to Charles Bab-bage’s steam-powered analytical engine You can use a computer without knowing anything at all about the workings of the underlying mechanism
However, if you know how it evolved to the point where it is now, you have
a much richer understanding of why it works the way it does For the same
reason, understanding how the design and architecture of web applica-tions has evolved provides valuable insight into how and why the architec-ture is sound
Part 1 covers the evolution of the architecture and design of state-of-the-art web applications It does not discuss servlets, JSP, and custom tag development from an API standpoint because plenty of other texts are available that focus on those topics Instead, we examine these APIs from
a design and architecture perspective, describing how to build web appli-cations that are scalable, maintainable, and robust Chapter 1 provides an overview of the topics for the entire book Chapter 2 covers the evolution
of web development in Java; chapter 3 explores that evolution through custom JSP tags Chapter 4 discusses the preferred design and architec-ture option, Model 2, along with some architectural options
Trang 5State-of-the-art
web design
This chapter covers
■ A brief history of Java web development
■ The importance of design patterns
■ An introduction to the Struts and Turbine
frameworks
■ A working definition of business rules
Trang 6The World Wide Web is a perfect example of how a simple idea (pages linked via hypertext) can lead to extraordinary richness Originally envisioned as a way to provide static pages (now affectionately known as “brochure-ware”), the medium quickly grew to embrace dynamic content These original efforts were written in languages like C and Perl As time and technology progressed, new application programming interfaces (APIs) sprang into existence, each building and improv-ing on the precedimprov-ing technologies New APIs appear because developers discover limitations in existing languages and tools Limitations in existing APIs led to the repurposing of Java for building dynamic web content, first as servlets, then as JavaServer Pages (JSP) The history leading from Perl, Common Gateway Inter-face (CGI), and C is well documented in just about every book on the servlet and JSP core APIs
Developers coming from more traditional application development (for exam-ple, client/server applications) discover that building web applications is funda-mentally different in many ways Even if you are fluent in Java, the architecture and design of web applications doesn’t necessarily come naturally Just as the switch from console applications to event-driven applications required a major shift in thinking, the switch from event-driven applications to the stateless world
of web development requires a paradigm shift as well Even an understanding of the basic infrastructure of web applications won’t immediately reveal the most effective architecture and design Many decisions made early in the design and development process have unforeseen repercussions later in the process Because
of the oft-quoted and well-documented cost of architectural and design changes late in the application lifecycle, it behooves you to get it right from the outset This chapter provides an overview of the topics we cover in this book First, we discuss the evolution of Java web development and the importance of design pat-terns Next, we examine web application frameworks (which are the topic of part 2 of this book) Finally, we examine best practices (the focus of part 3), along with a hot-button issue that falls under that heading The main goal of this book is
to show you how to apply best software-engineering practices to the development
of web applications in Java
1.1 A brief history of Java web development
Java began life as a programming language designed for building traditional applications and applets But as developers realized the benefits of Java, it
Trang 7A brief history of Java web development 5
quickly expanded into other realms of development, including distributed and web development
When Java took its first baby steps into the world of distributed web
applica-tions, it was with servlets The benefits of the servlet architecture have been
cov-ered extensively in other books, and we won’t rehash them here We are more
interested in why servlets were being used
In the beginning, developers used servlets to create dynamic web content Managers quickly realized that the talents that make a good Java developer do not necessarily overlap with the talents needed to create an attractive user interface (UI) in HTML (This isn’t unique to Java developers—Perl, C, and other develop-ers are similarly disadvantaged.) The pdevelop-erson you wanted designing the UI for your web application tended to be more of a layout expert, usually with a penchant for Macintosh computers So, to utilize the right people for the right jobs, managers had the art school folks crafting the UI while the Java developers worked on the functionality At some point the UI gurus passed their carefully crafted HTML to the Java developers to incorporate into the dynamic content This created a chal-lenge for the Java developers: merging the HTML from the art majors into the servlets that generated dynamic content
However, once this was done, the pain still wasn’t over Invariably, the presi-dent of the company would get a new online service disc in the mail over the weekend, stumble his way over to some web site he had never seen before, and come in on Monday morning with the mandate, “We’re changing the look and feel of our company web site.” The HTML coders had to implement the new Grand Vision Meanwhile, the Java developers realized that their job had just got-ten worse Now, not only did they have to merge the HTML into the servlets, they also had to selectively replace the existing HTML without breaking anything The
verdict on servlets was too much HTML mixed in with the Java code
Clever developers quickly cooked up their own template strategies Special markers in the HTML were parsed and replaced as needed In other words, the developers sprinkled special HTML comments into the UI, such as:
Customer Name: <! $customerName >
As the page displayed, the servlet would search through the code, looking for these “magic markers” to replace with dynamic content To render a page, the servlet was forced to parse and process the HTML before it was output to the browser Each development team created its own tags, so no level of standardiza-tion existed for the syntax and use of these custom tags Some companies created standard tags across development teams, but that was the extent of tag reusability
Trang 8Using templates is a big improvement because it separates dynamic content from the UI However, the approach suffers from a scalability problem Parsing HTML to render content is an expensive operation in terms of machine resources, including central processing unit (CPU) and input/output (I/O) subsystems For very busy web sites with lots of concurrent users, the I/O burden of parsing alone could grind the servlet engine to a virtual standstill Nonetheless, from a design standpoint, this was still better than mixing the HTML and Java together In fact, several template designers developed clever workarounds to this problem that still exist One such template system, Velocity, is discussed in chapter 9
This situation led to the development of JavaServer Pages JSPs validated the template concept and implemented a clever way around the expensive parsing operation JSPs are parsed only once, converted to a servlet, and then executed The template language for JSP consists of JavaBean components, scriptlets, and custom tags Developers discovered that they could now mix the logic and content more gracefully The idea was for the HTML developers to create the initial JSPs and then pass them to the Java developers to add the dynamic aspects Unfortu-nately, this led to another serious problem Because this process encouraged the mixing of UI and functional code, JSPs quickly degenerated into a maintenance nightmare I have seen too many JSPs that mortified and depressed me because of this coupling It is possible to create the worst possible type of coding horrors in JSP because it relies so much on “magic” symbols and encourages the unwhole-some mixture of code and UI The verdict on JSP is too much Java in the HTML
Fortunately, a solution to this problem already exists To get to the elegant answer to this issue, a diversion into design issues is called for
1.2 The importance of design patterns
In the mid-twentieth century, an architect named Christopher Alexander noticed
in his travels that architects tended to solve the same problems in more or less the
same ways This realization led him to the creation of a book of design patterns for
architects A design pattern “describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.” Alexander was talking about architecture in the
traditional sense, but in 1994 the book Design Patterns: Elements of Reusable
Object-Oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, and John
Vlis-sides (the “Gang of Four,” or “GoF”), applied Alexander’s ideas to software
Trang 9The importance of design patterns 7
design A pattern is a template that solves a particular problem that may appear in difference contexts In the GoF book, a pattern has the following characteristics:
1 The pattern name is a succinct, easy-to-remember moniker for the pattern.
The name is considered important because it becomes a part of the vocabu-lary of general design It should be one or two words and describe the essence of the pattern
2 The problem is a statement describing the difficulty and its context This
description includes all the details needed to understand the problem and the implications surrounding it, such as the class structure and a list
of conditions where this problem arises
3 The solution describes the software artifacts that solve this problem—design
elements, class and object relationships, aggregations, and collaborations
4 The consequences are the results and trade-offs of applying the pattern A
classic example of a trade-off is speed versus space The pattern should list all known consequences to allow developers to make an informed deci-sion as to whether they should use it
The GoF book was influential in the software community, and numerous books have appeared to carry on the identification of more patterns Design patterns are widely regarded as an evolutionary step beyond object-oriented programming (OOP) because they combine the atomic classes and objects defined by OOP into patterns that solve specific problems
1.2.1 The Model-View-Controller design pattern
If you are familiar with design patterns, you have probably heard of the Model-View-Controller (MVC) pattern MVC is the poster child for design patterns In the GoF book, MVC appeared in the introductory chapters as the example pattern MVC has its origins in Smalltalk, where it was used in the graphical user interface (GUI) for “traditional” (non-web) applications It is a design pattern for separat-ing data from its representation The developers of Smalltalk realized that it is a Bad Thing to have the data and the view of a system coupled together too closely Any change in either the data or the view requires changes to the other MVC mit-igates this problem by separating the parts of the system based on their function Figure 1.1 shows a graphical view of the artifacts that make up MVC
The model is responsible for the data and rules in the system It coordinates
business logic, database access, and all the other critical nonvisual parts of the system In a spreadsheet, the model represents the numbers and formulas that
Trang 10make up the data The view in MVC renders the display of the data In the spread-sheet example, you can look at the numbers in a grid, a chart, or a graph The numbers are the same; only the visual representation differs The grid can become a chart (or vice versa) without you touching the underlying values of the
numbers The controller is the mechanism by which the view and the model
com-municate In a spreadsheet, the controller can be the keyboard, the mouse, or some pen-based input device In any case, the controller changes the value shown
by the view and in turn changes the underlying model value The controller acts
as a conduit between the model and the view
A good example of MVC in action is the Swing UI controls in Java In Swing, each control (even components like JButton) has an underlying model that con-trols its content This is why it is so easy to change the look and feel of a Java appli-cation—you are changing the view without touching the model If you have written code for the more complex controls (like the JTable or JTree), you have ample experience in writing models In Java, models are most frequently imple-mented as interfaces You can think of the interface as a list of questions you must answer about the data being modeled If you can answer the questions, the con-troller can take care of rendering the correct view
123
582
7531
2
7345
91483
19
Model
70
Controller View
X-Axis
Keyboard
Mouse
Y-Axis Figure 1.1
The MVC design pattern separates the parts of an application into the model (the data), the view (the visual representation), and the controller (which allows the model and view to interact).