Chapter 2, Inside the Web Tier The Struts framework is based on the Java Servlet technology and, to a lesser extent, JavaServer Pages, andtherefore is tightly coupled to a web container.
Trang 1covers everything the successful earlier
edition did as well as plenty more: now fully
up to date with Struts 1.1, this edition covers the latest material on tag libraries and the new JavaServerFaces (JSF) APIs and even
includes all-new chapters on JSF, JSTL/EL,
Trang 2and security.
Trang 8Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
most titles (http://safari.oreilly.com) For more information,contact our corporate/institutional sales department: (800)
998-9938 or corporate@oreilly.com
Nutshell Handbook, the Nutshell Handbook logo, and the
O'Reilly logo are registered trademarks of O'Reilly Media, Inc.The Java Series, Programming Jakarta Struts, the image of apercheron, and related trade dress are trademarks of O'ReillyMedia, Inc
Java™ and all Java-based trademarks and logos are trademarks
or registered trade marks of Sun Microsystems, Inc., in the
United States and other countries Many of the designationsused by manufacturers and sellers to distinguish their productsare claimed as trademarks Where those designations appear inthis book, and O'Reilly Media, Inc was aware of a trademarkclaim, the designations have been printed in caps or initial caps
While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein
Trang 9Over the last few years, web development has turned a veryimportant corner Gone are the days when Java™ developerswrestled with a single JSP that contained presentation logic,database access via SQL, and navigational intelligence Javaweb developers have learned from their mistakes, paid the price
in debugging and maintenance time, and moved on
The number and variety of readily available web frameworkstoday is immense It's hard to point a browser at a Java
technical site without finding a newly released web frameworkthat's going to revolutionize the modern world While some maysee this as a bad thing that might divide the Java community,the truth is that the constant emergence of new frameworks isjust evolution at work
The design and construction of today's nontrivial web
applications pushes developers to the limit of what's logicallyand physically possible Myriad solutions are thrown at the
problems these applications present Some of the solutions
stick, and as with human evolution, valuable characteristics arepassed on in future generations of software Other solutions donotthose that fail to serve the needs of users and add value
usually fall by the wayside
Through this evolutionary process, the Jakarta Struts
framework (created by Craig R McClanahan and donated to theApache Software Foundation in 2000) has emerged as one ofthe best web frameworks available This book covers Version1.1, which contains many major enhancements over the
previous Jakarta Struts release If you are building applications,web-based or not, one of the main things you will learn fromthis book is that frameworks such as Struts are a great timeinvestment
Trang 10web-based applications
Chapter 1, Introduction
This chapter discusses some preliminary concepts, such asthe MVC pattern, Model 2, and the idea of a software
framework Although many developers may already be
familiar with some or all of the ideas presented here, I want
to ensure that all readers are starting from the same place.The concepts presented in this chapter help to lay the
foundation for the rest of the book
Chapter 2, Inside the Web Tier
The Struts framework is based on the Java Servlet
technology and, to a lesser extent, JavaServer Pages, andtherefore is tightly coupled to a web container For Strutsdevelopers, understanding how the web container processesclient requests is fundamental to understanding the
framework itself This chapter discusses the components ofthe web container and the responsibilities of each
Trang 11This chapter provides an overview of the Struts framework;
it does not attempt to cover all of the features or go intosignificant depth It emphasizes how all the pieces fit intothe MVC and Model 2 architecture presented in Chapter 1
Chapter 4,Configuring Struts Applications
The Struts framework uses two separate but somewhatrelated types of configuration files, which must be
configured properly before an application will function
properly Due to the popularity and flexibility of XML, bothtypes of configuration files are based on XML This chapterpresents the syntax of the files
Chapter 5, Struts Controller Components
The Struts framework uses a servlet to process incomingrequests; however, it relies on many other components thatare part of the controller domain to help it carry out its
resemble the real-world entities and business processes for
Trang 12responsibilities of the model components within the Strutsframework and focuses on building an architecturally correctimplementation for the Storefront application Special
client Based primarily on JavaServer Pages, the
components provide support for internationalized
applications as well as for user-input acceptance, validation,and error handling, all of which make it easier for the
developer to focus on business requirements This chapterconcludes the three-part discussion of how the Struts
framework implements the MVC pattern
Chapter 8, JSP Custom Tag Libraries
This chapter looks at the different categories of tags andhow they can help make developing applications with theStruts framework even easier It is not meant to be an
exhaustive reference for every tag that's part of the Strutstag librariesthat information can be found within the Strutsuser guide or JavaDocs The real purpose of this chapter is
to put forth the benefits of using the Struts tag libraries and
to provide a few strategies that can help make the switch tousing the tags less painful
Trang 13One of the biggest advantages of using a framework is theability to extend and customize it based on the needs of theapplication The Struts framework is no exception; it
provides several important extension points for developers.This chapter takes a quick glance at several of those
when things don't go as expected Special attention is given
to the differences between performing the exception
handling programmatically and using the new declarativefeature added to the Struts framework in Version 1.1
Chapter 11, The Validator Framework
This chapter introduces the Validator framework, which wascreated specifically to work with Struts components TheValidator allows you to declaratively configure validationroutines for a Struts application without having to programspecial validation logic
Chapter 12, Internationalization and Struts
This chapter focuses on what it takes to make a Struts
application available to customers from around the world,regardless of their language or geographical location As is
Trang 14Chapter 13, Struts and Enterprise JavaBeans
This chapter covers the issues you need to consider whendeveloping an interface between your Struts actions and anapplication tier It focuses on interfacing to a model builtusing Enterprise JavaBeans™ (EJB)
Chapter 14, Using Tiles
This chapter looks at the Tiles framework, which now is part
of the core Struts distribution The Tiles framework is anadvanced templating framework that reduces the amount ofredundant code a web application contains and allows
developers to better separate content from layout
Chapter 15, Logging in a Struts Application
This chapter examines how the use of logging in your Strutsapplications can help you identify defects before the
applications get into production and, if your software
already is being used in production, how logging can helpyou identify problems and arrive at solutions much morequickly
Chapter 16, Packaging Your Struts Application
Trang 15automate the build process for your environment Specialcoverage is given to Ant, the Java-based build tool availablefrom Jakarta
Chapter 17, Addressing Performance
This chapter explores the performance implications of usingthe Struts framework and its associated technologies to
build web applications and discusses how certain design andprogramming decisions affect the overall performance of theapplications It covers performance, load, and stress
overlap exists between Struts and JSF, there is plenty ofroom for both and this chapter explores what that
integration looks like
Appendix A, Changes Since Struts 1.0
This appendix enumerates the new features within the 1.1release
Appendix B, Downloading and Installing Struts
Trang 16Appendix C, Resources
This appendix lists several resources that can help increaseyour knowledge once you've mastered the concepts in thisbook
Trang 17Indicates a tip, suggestion, or general note.
Trang 18Indicates a warning or caution.
Trang 19This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Programming Jakarta Struts, Second Edition, by
00651-9."
Chuck Cavaness Copyright 2004 O'Reilly Media, Inc., 0-596-If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com
Trang 20Please address comments and questions concerning this book tothe publisher:
http://www.oreilly.com/catalog/0596006519
To comment or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about books, conferences, Resource
Centers, and the O'Reilly Network, see the O'Reilly web site at:
http://www.oreilly.com
Trang 21Writing a book of this type is never the work of just one person;
it literally takes an army of hardened soldiers, and this book is
no exception From the editors to the marketing organization tothe reviewers of the manuscript, this book simply would nothave been possible without the group of dedicated folks thatgave up many of their nights and weekends to help ensure thatthe quality was the highest possible Any credit should be given
to all of the great people involved; any mistakes are mine
alone
First, I need to thank my O'Reilly editors, Brett McLaughlin andRobert Eckstein, two of the most dedicated and sincere editorsthat I have worked with I hope we have a chance to work
together on future projects Your advice and leadership madethe task much easier than I could have imagined I also wouldlike to thank Kyle Hart from O'Reilly's marketing department.Your help was dearly appreciated
Next, I would like to acknowledge the team of fine developersthat I first learned Struts with The bond that our little NV teamhad was something special that comes around only once in awhile I really enjoyed working with all of you
The following people played a special role by giving me advice
on the book's content and direction: Steve Ardis, Jill Entinger,See Yam Lim, and Ted Husted (although Ted may not realizethat he contributed in this way)
When I first decided to post the draft chapters of the book, Imade a comment that if any reviewers went beyond the call ofduty, I would personally thank them in the acknowledgments ofthe book Little did I realize how many would take me up on it!There are so many that I can't thank each and every one
individually Over 100 people contributed feedback for one or
Trang 22of the best Almost every person on the Struts mailing list hascontributed in one way or another To each of you, thank you!
Thanks to the following people: John Guthrie, David Karr, BrentKyle, Stefano Scheda, and Rick Reumann for asking all the rightquestions, Mark Galbreath for reminding me of my 10th-gradeEnglish teacher, and James Mitchell and James Holmes for
getting me involved with the Atlanta Struts group
I need to say a special thanks to Tim Drury for his help on
Chapter 16 His Ant skills are known worldwide Special thanksalso to Brian Keeton, who wrote Chapter 13 because I'm tooslowhe's the smartest EJB developer I know Both of you aregreat friends and simply the finest humans that I've ever met.Just knowing you has made me a better person I hope we canwork together again
The group at TheServerSide.com deserves special thanks from
me and the reviewers for allowing the draft chapters of this
book to be available for download This is a great example ofwhat the future holds for book publishing
I would be remiss if I didn't thank the entire Struts community
I have met and corresponded with many smart developers whoalso strike me as just really fun people to hang around with.The feedback and suggestions I received during this processwere awesome I hope that all of you got some benefit out ofthis, and I appreciate everyone's patience while some of thiswas figured out as I went
Finally, all Struts developers should give thanks to Craig
McClanahan for having the wits about him to create the
framework and make it freely available to the community Hecould have tried to make a profit from it by starting Struts, Inc.,but he realized that he would be rewarded ten-fold anyway, andI'm sure he has been Craig, it's a nice framework, you should
be proud And to all of the committers on the Struts project,
Trang 23what would it really be without you? Thanks for all of your help.
Trang 24The Struts open source framework was created to make it
easier for developers to build web applications based on theJava Servlet and JavaServer Pages (JSP) technologies Like abuilding, a web application must have a solid foundation fromwhich the rest of the structure can grow The Struts frameworkprovides developers with a unified infrastructure upon whichInternet applications can be based Using Struts as the
foundation allows developers to concentrate on building thebusiness application rather than on the infrastructure
The Struts framework was created by Craig R McClanahan anddonated to the Apache Software Foundation (ASF) in 2000 Theproject now has several committers from around the world, andmany developers are contributing to the overall good of theframework The Struts framework is one of many well-knownand successful Apache Jakarta projects Others include Ant,
log4j, and Tomcat The overall mission of the Jakarta project is
to provide commercial-quality server solutions, based on theJava platform, in an open and cooperative fashion
Trang 25No book on web technology would be complete without a brieflook at how the World Wide Web (WWW) has become as
popular as it is today The Web has come a long way since thedays when the first hypertext documents were sent over theInternet In 1989, when the physicists at the CERN laboratoryproposed the idea of sharing research information between
researchers using hypertext documents, they had no idea howbig the Web would grow or how essential it would become todaily life for much of the industrialized world The Web is now
an accepted part of our vernacular
It took a while for the benefits of using the Web to become
clear to others outside of CERN, but as we all know, it
eventually erupted into what we use today From its beginnings,the Web was designed for dealing with static documents, but itwas a natural progression to want the ability to generate
document content dynamically The Common Gateway Interface
(CGI) was created to do that very thing CGI is a standard thatallows web servers to interact with external applications in such
a way that hypertext pages no longer have to be static A CGIprogram can retrieve results from a database and insert thoseresults as a table in a hypertext document Likewise, data
entered into a hypertext page can be inserted into the
database This technology opened up infinite possibilities and,
in fact, started the Internet craze of the mid-1990s and today
Although CGI applications are very good at what they do, thereare some serious limitations to this approach For one thing,CGI applications are very resource-intensive A new operatingsystem (OS) heavyweight process is created to handle everyrequest that comes from a browser Once the CGI script is
finished executing, the process has to be reclaimed by the OS.This constant starting and stopping of heavyweight processes isterribly inefficient You can imagine how bad the response time
Trang 26to the same web application Another major limitation of CGI isthat it's difficult to link to other stages of request processing,because it is running in a separate process from the web server.This makes it difficult to handle things such as authorization,workflow, and logging
A few alternatives to standard CGI applications have been put
forward One alternative is FastCGI, a language-independent
extension to CGI that doesn't have the same process model asstandard CGI It's able to create a single heavyweight processfor each FastCGI program, allowing multiple requests to runwithin the same process space However, when clients interactconcurrently with the same FastCGI program, the program
needs to create a pool of processes to handle each request This
is not much better than standard CGI Another problem withFastCGI applications is that they're only as portable as the
languages in which they are written Other alternatives to CGIinclude mod_perl for Apache, NSAPI for Netscape, and ISAPI forMicrosoft's IIS web server While these solutions often offer
better performance and scalability than standard CGI programs,they still have portability issues
In 1997, while the Java language was experiencing tremendousgrowth and use by application developers, the Java Servlet
technology was created This new web technology opened up anentirely new avenue for web developers to explore
Trang 27Java servlets have become the mainstay for extending and
enhancing web applications using the Java platform They
provide a component-based, platform-independent method forbuilding web applications Servlets don't suffer from the sameperformance limitations that standard CGI applications incur.Servlets are more efficient than the standard CGI threadingmodel because they create a single heavyweight process andallow each user request to use a much more lightweight thread,which is maintained by the Java Virtual Machine (JVM), to fulfillthe request Multiple user requests can be threaded through thesame instance of a servlet A servlet is mapped to one or more
uniform resource locators (URLs), and when the server receives
a request to one of the servlet URLs, the service method in theservlet is invoked and it responds Because each user request isassociated with a separate thread, multiple threads or users caninvoke the service method at the same time This multithreadednature of servlets is one of the main reasons that they are morescalable than standard CGI applications Also, because servletsare written in Java, they are not proprietary to a platform orOS
Another significant advantage of being written in the Java
language is that servlets are able to exploit the entire suite ofJava application programming interfaces (APIs), including JavaDataBase Connectivity™ (JDBC) and Enterprise JavaBeans
(EJB) This was one of the factors in servlets becoming part ofthe mainstream so quickly; there already was a rich Java library
in place for them to leverage
Servlets are not executed directly by a web server They require
a servlet container, sometimes referred to as a servlet engine,
to host the servlet This servlet container is loosely coupled to aparticular instance of a web server, and together they cooperate
to service requests Figure 1-1 illustrates how a web server and
Trang 28Figure 1-1 Processing a client request
Developers are free to choose from one of many servlet
containers available to host their servlets; they are not lockedinto a particular vendor or platform Servlets can be ported toany of these containers without recompiling the source code.This leads to a "best of breed" solution for web applicationsyouget the best product or component for a specialized need, while
at the same time avoiding the high risk normally associatedwith a single solution
There are several popular servlet containers on the market.Some are standalone servlet containers that must be connected
to an external web server to work, while others provide boththe web server and servlet container in the same product
There are even a few that are integrated into application
servers and provide much more functionality than just a servletcontainer Table 1-1 lists some of the more popular servlet
containers Some of the products in this list are commercialproducts while others listed have a small or insignificant cost touse
Table 1-1 Popular servlet containers
Trang 29Although servlets are great at what they do, it quickly becameapparent that hardcoding HyperText Markup Language (HTML)output in a servlet as a response to a request had some seriouslimitations First and foremost, it was hard to make changes tothe HTML because for every change, a recompilation of the
servlet had to take place
Secondly, supporting different languages is difficult because theHTML is hardcoded Determining the user's language, region,
Trang 30servlets, one for each supported locale
[1] Interrnationalization is commonly referred to as "I18N" because the word begins with the
letter I, ends with the letter N, and contains 18 characters in between.
Finally, because HTML was embedded within the servlet, therewas a problem with responsibility Web designers build HTMLpages; they are not usually experienced with Java
programming, let alone skilled at object-oriented design andprogramming When you mix HTML and Java code within theservlet, it becomes hard to separate the page design and
programming duties Even when a developer has the necessaryskills to perform both functions, modifications to the page
layout require recompilation, which adds to development andtesting time
Servlet programming is such a broad topic that it can't be
covered in great detail here If you feel that you need moreinformation on Java Servlet technology, a great source of
material is Jason Hunter's Java Servlet Programming (O'Reilly).
You can also find more information at the Sun Servlet web site
(http://java.sun.com/products/ servlet/index.html)
JavaServer Pages was the next step in the linear progression ofdeveloping web technologies based on the Java platform Theintroduction of JSP pages, as they are commonly referred to,helped to alleviate the servlet limitations mentioned earlier andopened up many new doors for web developers
Trang 31The first thing to understand about JavaServer Pages is that it's
a natural extension to the Java Servlet technology In fact, aftersome preprocessing by a translator, JSP pages end up beingnothing more than Java servlets This is a point that many
beginning developers have a hard time understanding JSP
pages are text documents that have a jsp extension and
contain a combination of static HTML and XML-like tags andscriptlets The tags and scriptlets encapsulate the logic that
generates the content for the pages The jsp files are
preprocessed and turned into java files At this point, a Java compiler compiles the source and creates a class file that can
Trang 32JSP is a specification, not a product Developers are able tochoose a "best of breed" approach
JSP pages are compiled, not interpreted, which can lead tobetter performance
JSP pages support both scripting and access to the full Javalanguage and can be extended through the use of customtags
JSP pages share the Write Once, Run Anywhere™
characteristics of Java technology
As mentioned in the previous section, one of the limitations ofusing hardcoded HTML inside of servlets is the problem of
separating page design and application logic programming
responsibilities This separation is easier with JSP pages,
because the HTML designers are free to create web pages withwhatever tools they choose (many of today's popular tools arecapable of working with JSP and custom tags) When they arecomfortable with the page layout, the JSP developers can insert
JSP scriptlets and custom tags and save the files with a jsp
extension That's pretty much all there is to it When the timecomes to change either the page layout or page logic, the
developer modifies the JSP page as needed and allows it to berecompiled automatically
Together, JSP pages and servlets are an attractive alternative toother types of dynamic web programming Because both arebased on the Java language, they offer platform-independence,
Trang 33extensibility into the enterprise, and, most importantly, ease ofdevelopment.
Trang 34Many developers believe custom tags, rather than scriptlets or expressions, should be used in JSP pages The rationale is:
Scriptlets mix logic with presentation.
Scriptlets break the separation of roles.
Scriptlets make JSP pages difficult to read and maintain.
Custom tags, on the other hand, centralize code in one place and help maintain the separation of responsibilities They also support the concept of reuse, as the same tag can be inserted into multiple pages while the implementation resides in
a single location There also is less redundancy and potential for copy-and-paste errors with custom tags.
Trang 35a request is handled With the Model 1 architecture, the JSPpage handles all of the processing of the request and is
responsible for displaying the output to the client This is
illustrated in Figure 1-3
Figure 1-3 JSP Model 1 architecture
Notice that there is no servlet involved in the process The clientrequest is sent directly to a JSP page, which may communicatewith JavaBeans or other services, but ultimately the JSP pageselects the next page for the client The next view is determinedbased on either the JSP selected or parameters within the
client's request
Trang 36controller servlet This servlet handles the initial processing of
the request and determines which JSP page to display next.This approach is illustrated in Figure 1-4
completed, the servlet directs the request to the appropriateJSP page How the next page is determined varies widely acrossdifferent applications For example, in simpler applications, thenext JSP page to display may be hardcoded in the servlet based
on the request, parameters, and current application state Inmore sophisticated web applications, a workflow/rules enginemight possibly be used
Trang 37Model-View-Controller (MVC) pattern.
One of the key arguments against using the MVC approach isthat it seems overly complicated While at first glance thismight appear to be true, using a MVC strategy can actuallysimplify application design and construction Web applicationsbuilt using the Model 2 approach are generally easier to
maintain often more extensible than comparable applicationsbuilt around the Model 1 architecture
Trang 38The MVC architectural pattern is not directly related to web
applications or Java for that matter In fact, it's quite common
in Smalltalk applications, which generally have nothing to dowith the Web
As we saw in the previous section, the Model 2 approach is
concerned with separating responsibilities in web applications.Allowing a JSP page to handle the responsibilities of receivingthe request, executing some business logic, and then
determining the next view to display can make for an
unattractive JSP page, not to mention the maintenance and
extensibility problems this entanglement causes Applicationdevelopment and maintenance are much easier if the differentcomponents of a web application have clear and distinct
responsibilities
The MVC pattern is categorized as a design pattern in manysoftware design books Although there is much disagreement onthe precise definition of the pattern, there are some
Trang 39Responsible for controlling the flow and state of the userinput
With the MVC pattern, a form of event notification usually takesplace to notify the view when some portion of the model
changes However, because a browser in a typical web
application has a stateless connection, the notification from themodel to the view cannot occur easily.[2] Of course, an
application could perform some type of push mechanism to
push notification or data all the way to a client, but this is
overkill for most web applications A user can close the browser
at any time, and generally no notification is sent to the server Agreat deal of overhead is necessary to manage remote clientsfrom the server side This type of behavior is not necessary fortypical web applications
[2] Web applications are considered stateless because the browser doesn't maintain a constant
open connection to the web server However, a web application still may maintain session data for
a user or even store data within the browser on behalf of the user.
With standard web applications, a client typically sends anotherrequest to the server to learn about any changes to the model.This is known as a "pull" approach For example, if a user isviewing pricing information for an item and at the same timethe administrator changes the price for that item, the user willnot know it changed until he refreshes the page
1.5.1 The MVC Model
Depending on the type of architecture your application uses, themodel portion of the MVC pattern can take many different
forms In a two-tier application, where the web tier interactsdirectly with a data store such as a database, the model classes
Trang 40by an object-to-relational mapping (ORM) framework such as
TopLink or CocoBase
In a more complex enterprise application (where the web tiercommunicates with an EJB server, for example), the model
portion of the MVC pattern will be Enterprise JavaBeans
Although the EJB 2.0 specification made performance
improvements through the use of local interfaces, there still can
be a significant performance impact if the web tier attempts touse entity beans directly as the model portion of the
application, due to the overhead of making remote calls In
many cases, JavaBeans are returned from session beans andused within the web tier These JavaBeans, commonly referred
to as data transfer objects, are used within the views to buildthe dynamic content
1.5.2 The MVC View
The views within the web tier MVC pattern typically consist ofHTML and JSP pages HTML pages are used to serve static
content, while JSP pages can be used to serve both static anddynamic content Most dynamic content is generated in the webtier However, some applications may require client-side
JavaScript This does not interfere with or infringe upon theMVC concept
HTML and JSP are not the only choice for the view You easilycan support WML, for example, instead of HTML Because theview is decoupled from the model, you can support multipleviews, each for a different client type, using the same modelcomponents