Java servlets are fast becoming indispensable enterprise components, as they provide a means to build scalable and portable business services that security, scalability, performance and
Trang 1Professional Java Servlets 2.3
by Andrew Harbourne- Thomas et al
ISBN:186100561X
APress, LLC © 2004 (700 pages)
For Java programmers who are moving into working with J2EE components and want
to learn how to apply their skills to create real-world web components, this guide has it all!
Trang 3Java servlets are fast becoming indispensable
enterprise components, as they provide a means to build scalable and portable business services that
security, scalability, performance and design It walks you through the API covering the role of all the classes and interfaces and provides lots of example
applications to demonstrate servlets in action The
book also covers the key role that servlets play in the new web services development model.
Trang 4The effects of classloading and synchronization on the behavior of web applications
Optimizing the performance of web applications Using servlets as agents with web services
Trang 5Printed and bound in the United States of America 10987654321
Trademarked names may appear in this book Rather than use a
trademark symbol with every occurrence of a trademarked name, we usethe names only in an editorial fashion and to the benefit of the trademarkowner, with no intention of infringement of the trademark
Distributed to the book trade in the United States by Springer-Verlag NewYork, Inc., 175 Fifth Avenue, New York, NY, 10010 and outside the UnitedStates by Springer-Verlag GmbH & Co KG, Tiergartenstr 17, 69112
Trang 6In the United States: phone 1-800-SPRINGER, email <ny.com>, or visit http://www.springerny.com Outside the United States: fax+49 6221 345229, email <orders@springer.de>, or visit
orders@springer-http://www.springer.de
For information on translations, please contact Apress directly at 2560Ninth Street, Suite 219, Berkeley, CA 94710 Phone 510-549-5930, fax510-549-5939, email <info@apress.com>, or visit http://www.apress.com.The information in this book is distributed on an "as is" basis, withoutwarranty Although every precaution has been taken in the preparation ofthis work, neither the author(s) nor Apress shall have any liability to anyperson or entity with respect to any loss or damage caused or alleged to
be caused directly or indirectly by the information contained in this work.The source code for this book is available to readers at
Trang 7Production Coordinator
Tom Bartlett
Illustrations
Trang 8Indian Institute of Technology, to Computervision, and Wipro Infotech,and later to BEA Systems You can find more about his current activities
at his home http://www.Subrahmanyam.com
Subrahmanyam would like to thank Varaa for her hand in code samples (in the face of tight deadlines), and sharing his
frustration as well as exhilaration.
Subrahmanyam contributed Chapter 5 to this book
John T Bell
John Bell is a Principal Engineer at Latitude360, a subsidiary of RWDTechnologies He has been providing technology solutions for over 20years and has been developing Java-based web systems for the pastseveral years His primary areas of expertise are in object-oriented
development and distributed processing systems Recently he has beensupporting DaimlerChrysler as lead architect for a number of Java-basedweb platform initiatives He is now supporting Latitde360's own eLearningproduct development efforts He has a Bachelor's degree in ElectricalEngineering and a Masters degree in Computer Systems Management,both from the University of Maryland In his spare time he plays with hiskids, maintains computers for local charities, and writes strategy basedcomputer games He is also active in the Christian and Missionary
Alliance Church
Trang 9been published on JavaWorld and co-authored the 2nd Edition of
Professional JSP
Simon graduated from the University of Reading in 1996 with a First
Class BSc (Hons) degree in Computer Science He has also attainedmany Sun certifications, including the Sun Certified Enterprise Architectfor J2EE, Web Component Developer for J2EE and Developer for theJava 2 Platform Feel free to e-mail any questions or comments to
<projavaservlets@simongbrown.com.>
I would once again like to thank my fiancée Kirstie for her
encouragement, and also for putting up with me being tucked away in the spare room for hours at a time.
Simon contributed Chapter 12 to this book
Sam Dalton
Sam is a Technical Architect, and is based in London He has workedwith Java and related technologies for a number of years, in various
industries, including investment banking, insurance, and retail e-commerce
Sam was fortunate enough to present and co-present several very
popular sessions at JavaOne in 2001, and hopes to make many moreappearances in the future
Trang 10Many heartfelt thanks go to my wife Anne, who is always very supportive of my efforts, and always there with a nice cup of tea!
Sam contributed Chapter 4 to this book
Andrew Harbourne-Thomas
Andrew Harbourne-Thomas is an independent consultant focusing onJ2EE application design and development and project management Hestarted working life as an economist, worked as Economic Advisor to theIrish Trade Board (now Enterprise Ireland), followed by several yearsworking as an independent consultant to top companies including
Microsoft, focusing on technology, strategy and project management
He was always interested in evolving technologies and has been workingwith Java technologies since 1997, including some time with Bear
Stearns IT division His main interests include J2EE application
architecture, web service design, extreme programming, and emergingtechnologies
Andrew lives in Dublin, Ireland, and while escaping from Java; his mainpursuits include scuba diving and photography
he is taking time off from work to pursue his studies of electrical
engineering and occasional writing opportunities
Bjarki contributed Chapter 6 to this book
Trang 11Meeraj works as a Senior Information Specialist with EDS He designsenterprise helpdesk and billing systems using J2EE and XML
I dedicate my work for this book to the three most wonderful women in my life: my mother, my wife and my sister May Allah bless the entire humankind.
Meeraj contributed Chapters 8 and 13 to this book
Sing Li
First bitten by the computer bug in 1978, Sing has grown up with themicroprocessor and the Internet revolution His first PC was a $99 do-it-yourself COSMIC ELF computer with 256 bytes of memory and a 1 bitLED display For two decades, Sing has been an active author,
consultant, instructor, entrepreneur, and speaker His wide-ranging
experience spans distributed architectures, web services, multi-tieredserver systems, computer telephony, universal messaging, and
embedded systems Sing has been credited with writing the very firstarticle on the Internet Global Phone, delivering voice over IP long before
it becomes a common reality He has been working with (and writingabout) Java, Jini and JXTA since their very first available releases, and is
an active evangelist for the unlimited potential of P2P system technology.Sing contributed Chapters 7 and 9 to this book
Tony Loton
Tony Loton is Principal Consultant / Director of LOTONtech Limited
(http://www.lotontech.com)
He works through his company as an independent consultant, traininginstructor, and freelance author, and the current areas of interest at
LOTONtech include Java-based speech synthesis and the automatedextraction of information from the World Wide Web
Tony holds a bachelors degree in Computer Science and Managementand has over ten years IT experience, five or more working with Java,
Trang 12I dedicate my contribution to my children, Becky and Matt, the lights of my life.
Tony contributed Chapters 10 and 11 to this book
Trang 13applications, keep track of users of an application, intercept and modifyrequests and responses, and interact with web services
With the development of the 2.3 version of the Servlet specification
(finalized in September 2001), the expert group have made a number ofchanges including:
javax.servlet.http.HttpUtils class
The Servlets 2.3 API specification is also a key component in the Java 2Patform, Enterprise Edition (J2EE) 1.3 specification, and as we will see in
Trang 14As we go along, we'll explain these concepts thouroughly, using plenty ofcomplete, working examples to demonstrate their use
Trang 15This book is aimed at developers who are familiar with the Java languageand the core Java APIs It is assumed that readers are familiar with somebasic HTML and XML - although this isn't essential We'll be using thelatest specification of Java Servlet technology - version 2.3
Servlets are rarely used in isolation but this book does not claim to beexhaustive in all areas, particularly in relation to other Java technologies
and APIs such as JDBC, JNDI, and JavaServer Pages Professional
Java Server Programming J2EE 1.3 Edition (ISBN 1-861005-37-7)
provides an excellent introduction to the whole J2EE platform
Trang 16The book has the following structure:
We start with an overview of how and where servlets fit into theenterprise
Chapters 2 and 3 cover the Servlet 2.3 API We'll look at thelifecycle of servlets and understand how we can comsume andgenerate HTTP requests and responses
Although we'll have been running applications in earlier chapters,Chapter 4 explains the structure of a web application and how weshould deploy them on a web server
how we can maintain sessions, how we can persist servlets, and
Chapters 5–7 look at some of the powerful features of servlets -filters.
In Chapter 8 we'll look at JavaServer Pages (JSP), which is atechnology that is complimentary to Java Servlets
Chapters 9-11 will be spent looking at some of the issues thatarise when web applications are deployed in production
environments We'll look at debugging techniques we can use totrack down problems with our servlets and we'll understand theproblems that can occur if we don't consider the effects of
classloading and synchronization
In Chapters and 13 we'll look at how the design of our web
applications can affect the performance and maintainability We'lllook at the various patterns we can use to create better
applications and we'll look at some techniques and tools we canapply to improve the performance and scalability of our web
applications
Finally, in Chapter 14 we'll look at how we can use servlets as
agents, to access information from web services.
Trang 18Most of the code in this book was tested with the Java 2 SDK version 1.3(http://java.sun.com/j2se/1.3/) and Apache Tomcat 4
(http://jakarta.apache.org/tomcat/) However, running the examples in somechapters will require some additional software
Several of the chapters require access to a database For these chapters
we have used MySQL (version 3.23) and the MM.MySQL JDBC driver(version 2.0.6) You can download both of these from
http://www.mysql.com The download includes full installation instructions.There are several other pieces of software that a couple of chapters alsorequire:
Apache SOAP 2.2 - from http://xml.apache.org/soap/index.html
Apache AXIS - from http://xml.apache.org/axis/index.html
The code in the book will work on a single machine, provided it is
networked (that is, it can see http://localhost/ through the local browser).The complete source code from the book is available for download from:
http://www.apress.com/
Trang 21We value feedback from our readers, and we want to know what youthink about this book: what you liked, what you didn't like, and what youthink we can do better next time You can send us your comments by e-mailing <support@apress.com> Please be sure to mention the book's
ISBN and title in your message
Source Code and Updates
As you work through the examples in this book, you may choose either totype in all the code by hand, or to use the source code that accompaniesthe book Many readers prefer the former, because it's a good way to getfamiliar with the coding techniques that are being used
Whether you want to type the code in or not, it's useful to have a copy ofthe source code handy If you like to type in the code, you can use oursource code to check the results you should be getting - they should beyour first stop if you think you might have typed in an error By contrast, ifyou don't like typing, then you'll definitely need to download the sourcecode from our web site! Either way, the source code will help you withupdates and debugging
Therefore all the source code used in this book is available for download
at http://www.apress.com Once you've logged on to the web site, simplylocate the title (either through our Search facility or by using one of the titlelists) Then click on the Source Code link on the book's detail page andyou can obtain all the source code
The files that are available for download from our site have been archivedusing WinZip When you have saved the attachments to a folder on yourhard drive, you need to extract the files using a de-compression programsuch as WinZip or PKUnzip When you extract the files, the code is
usually extracted into chapter folders
Errata
Trang 22be helping us provide even higher quality information To find known
errata and submit new errata, simply go to the appropriate book page onthe Apress website at http://www.apress.com
forums.apress.com
For author and peer discussion, join the Apress discussion groups If youpost a query to our forums, you can be confident that many Apress
authors, editors, and industry experts are examining it At
forums.apress.com you will find a number of different lists that will help you,not only while you read this book, but also as you develop your own
applications
To sign up for the Apress forums, go to forums.apress.com and select theNew User link
Trang 23Chapter 1: Servlets in the Enterprise
Trang 24with Java 2 Platform, Enterprise Edition (J2EE) In fact we're going to concentrate on one part of J2EE - the Java Servlet 2.3 API.
J2EE builds upon J2SE, providing APIs and services for developing anddeploying enterprise applications Together the services and libraries ofJ2SE and J2EE enable the development of platform-independent, web-based Java applications The J2EE platform also enables server vendors
to provide environments in which the J2EE applications can be deployedand run
In this chapter we're going to begin by considering enterprisearchitecture with distributed applications, and the tiers involved inweb application development
We will then examine how the J2EE architecture facilitates webdevelopment via web containers and Java servlets, and discussthe J2EE services and libraries that servlet developers may want
to consider including in their applications
We will also discuss the advantages of using Java servlets thatcomply with the Servlet 2.3 specifications in our web applications.This will lead to a discussion of the roles that container vendorsand developers have to play in implementing the Servlet
specifications, and an introduction to the Tomcat web
container/server, which is the reference implementation of theServlet specifications
To round off the chapter, we will take a look the roles that servletshave to play in modern enterprise applications, which should
Trang 25However, before we begin to look at servlets in detail, let's take a highlevel view of enterprise architecture
Trang 26Today the architecture and infrastructure of an enterprise-scale
application can be extremely diverse An enterprise can consist of legacymainframes from the 1960's coupled with modern systems Over the pastdecade legacy and modern systems have been integrated using
networks and the Internet
Businesses retain their legacy systems because the economic cost oftransferring their core business practices to a modern system is
prohibitive However, the consequence of maintaining legacy systems,introducing new systems, and merging them with systems from otherorganizations is that the architectural landscape of the enterprise is
complicated
Consider a financial services company that has existed for 30 years.Thirty years ago, it defined its core business processes on a mainframesystem in COBOL Over the years the company was involved in severalacquisitions and mergers, and the business processes of these othercompanies were integrated with the system These businesses
developed applications using the best technology available at the time.The result is that today the company has a complex architecture thatlinks many diverse hardware and software systems Of course, thesesystems not only have to link up internally, but also externally via theWeb
The distributed environment of the Web allows employees working at a
PC in their office to interact with any other connected system or resource,both within and outside the business External systems (for example,those of suppliers) can be included in the network and hence
communicate with the enterprise employees and systems through theWeb The problem is then to establish a common language or protocol toenable these systems to communicate
Networks and Protocols
In developing for distributed computing systems, the underlying physical
Trang 27developer Java's "write once, run anywhere" philosophy has led to thedevelopment of a strong arsenal of network-related API that makes
development of distributed applications easier, making a basic
understanding of the topology of the network over which we developimportant As we begin to work with servlets in a distributed environment,
we start by looking briefly at the physical connections made betweencomputers and how our systems are linked
In a network, all linked systems are connected - whether by physical orwireless network The network serves as a link for communication
between computer systems and the software that runs on them Threebasic network topologies are shown in the following diagram:
topologies being a derivative or combination of these As new networkingand communication technologies evolve, such as Bluetooth, the topology
of the enterprise network tends to become more complex The demands
Trang 28Any resource can join the network, so long as it can communicateusing the protocol(s) agreed for the network
A protocol is a set of rules agreed for communication A number of
protocols have been developed to specify common standards and
message formats, so that different systems can exchange informationand data These protocols were designed to provide specific services andare layered to provide a (relatively) reliable networking service
At the physical level, the hardware physical connection takes place
between the communicating computers This essentially comprises thenetwork cards and the wired (or wireless) connection between the
systems This allows the computers to communicate by providing a
medium over which messages can travel
At the network layer, the network implements a protocol such as the
Ethernet to facilitate communication between the computers This dealswith how data should be broken into frames and sent across the network
Trang 29breaking up and reassembling large messages, and how to deal withnetwork problems
Messages sent from one system are wrapped up in the layered protocolsand then sent across to the another system via the network The systemthat receives the message unwraps the message from within the layers
of protocol Logically, each equivalent layer is communicating with itscorresponding level on the other computer Each of these layers are, atthe most basic level, providing a bridge between the systems, and theprotocol layers above them provide additional services
It is a little like a more reliable version of translation where the top levelscommunicate in the home language, but the message must be translatedinto a series of intermediate languages or codes before it can be
exchanged The receiver then sends the message back through a
defined series of translators or decoders, until the message has beentranslated into the home language again
TCP/IP
The Transmission Control Protocol (TCP) and the Internet Protocol (IP) layers are commonly grouped together because the two protocols
provide complementary services The TCP/IP protocols are by no meansthe only protocols that can be used for these layers, but they have, as theWeb has developed, become the standard protocols for communicationover the Web
The Internet Protocol defines how pieces of data (known as packets) are
formatted, as well as a mechanism for routing the packet to its
destination This protocol uses IP addresses of connected computers inthe routing of data across the network This is a relatively unreliable
protocol, as data can be lost or arrive out of sequence The TransmissionControl Protocol provides the application layer with a connection-orientedcommunication service This layer provides the reliability that the
underlying IP layer lacks, by ensuring that all packets of data are
received (and resent if necessary) and are reassembled in the correctorder
Trang 30applications can communicate with most servers with confidence that themessage will be understood
HTTP provides a defined format for sending and receiving requests, andacts as a common language that applications and systems developed ondifferent systems and in different languages can all understand
Why Not Use Remote Procedure Calls?
Remote Procedure Calls (RPC) is a mechanism by which a client can
make specific requests to a program on a server (passing variables asrequired) The server then returns a result to the client that made therequest The client that makes a call must follow a predefined format
In Java, RPC is implemented in Remote Method Invocation (RMI), by
which Java applications can invoke methods of a class on a remote
server according to the process defined for RMI method calls This isdone with the use of interfaces that define the remote object whose
methods we want to call The request is then made on the remote object,with the help of the interface, as if it was a local object Java uses
vendor-provided custom protocol implementations to convey the request.Sun uses the Java Remote Method Protocol over TCP/IP Alternatively,RMI method invocation may be carried over the IIOP (Internet Inter-OrbProtocol) between Java applications (RMI-IIOP), which is language
independent, allowing interaction using a remote interface with any
Trang 31involved in RPC type requests, you frequently have to update both theclient and server classes, even if the change only affected one side WithHTTP, so long as the format of requests is agreed, the server updates donot need any modification on the client (and vice versa)
HTTP is the standard language of the web, used and understood bymore servers and clients This makes it the ideal protocol to use formost web and servlet development
Tiered Architectures
The old model of two-tiered client-server development, where the clientapplication connected directly with the data source, has been largelysuperceded Enterprise applications are becoming more prevalently
multi-tiered applications, spanning three or more tiers The separationand consolidation of logical parts of the application into many differenttiers has a couple of key benefits:
By modularizing functions into specific tiers, we encapsulate
related rules and functionality together, enabling easier
maintenance and development
Trang 32development
Developers with particular skills can focus on the logic specific to
a particular tier (for instance database specialists can focus onthe database tier), while the contract between tiers defines therelationships between tiers, and what services they can expectfrom the other tiers
The business tier is responsible for holding the business
processing logic It is concerned with implementing the businessrules for the application faithfully
The web tier (or presentation tier) is reserved for presenting or
wrapping the business data for the client It responds to the clientrequests and forwards them to the business tier where the
business logic is applied to the processing of the request
The business tier will return the outcome of the request (data or otherresponse) and the web tier will prepare the response for the client
Trang 33In Java terms, we have a developer-friendly situation where the provision
of the services and APIs that support them have been standardized
across compliant Java servers This means that we can start applicationdevelopment on one standards-compliant server, and then deploy theapplication on another compliant server from a different vendor with littledifficulty
This is where the Java 2 Platform, Enterprise Edition comes into the
picture This is not a server, but a set of specifications for technologies,services, and architecture that a J2EE-compliant server must provide.From a programmer's point of view this allows us to focus on developingthe application rather than having to learn about how it interacts with theserver Different vendors do provide additional services and tools on their
Trang 34services and APIs provided for by the J2EE specifications
Servlets are an integral part of J2EE They sit on the web tier responding
to, and processing, client requests They provide the client tier with astandard gateway to the information available from the business or
database/enterprise information tier They can service many types ofclients in a standard request-response cycle over any suitable protocol(such as HTTP)
Servlets are responsible in the J2EE model for providing dynamic content
to the client This means that they are the bridge between the client andthe web application, and their main service is to exchange and transferdata with the client in the standard request response structure As part ofthis process they receive client requests, usually with some additionalinformation (for example request parameters) Then they process thisinformation, communicating with other sources required to process thedata, such as databases, or other information sources Finally they return
a response to the client
Trang 35The J2EE architecture views an application as a collection of related yetindependent components, that interact with one another through the
responsibility is to develop the components, within the context of thecontainer The application developer does not need to understand
specifically how the container receives requests (over socket
connections) and maps them to a specific resource or any of the otherresponsibilities of the container The J2EE container has this
responsibility and the developer has only to worry about their specificcomponents and application
J2EE Container Types
Trang 36
of the design The J2EE server provides specific containers for differentcomponent types Business logic can be modularized and reused wherepossible, without having to directly manage any of the low level
based web server that provides a web container for our web application
The middle tier is managed by a J2EE application server This is a Java-To be J2EE platform compliant it will also offer a J2EE EJB container andaccess to J2EE APIs such as JDBC, JNDI, and JAAS (more on theselater) It may offer additional services or resources specific to the vendor,but at a minimum will comply with the J2EE specifications BEA
WebLogic Server, IBM WebSphere Application Server and the iPlanetApplication Server are examples of J2EE application servers
This application server manages two containers The web container contains and provides the services for the web components The EJB (Enterprise JavaBean) container is the business tier of the J2EE
platform This is where the business logic resides
Trang 37Client Containers
When considering client containers it is important to remember that J2EEclients need not be J2EE-specified clients The J2EE specifications donot mention Java 2 Platform, Micro Edition (J2ME) clients that may run
on smaller hand-held devices (for instance cell phones or PDAs) andcould be suitable clients for a J2EE server There may be other non-Javaapplications or servers, or even J2EE servers, acting as clients
For example, there may be an existing client-server-database three-tierapplication already running successfully in a company As the businesschanges and develops, the business rules and logic governing this
application may change and it may be better to rewrite part or all of theapplication It may be simplest to rewrite the server side of the equationbecause this may be all that is affected, while the database and client(written in another language possibly) may be left unchanged The clientmay be rewritten at a later stage, but users may be happy with the client
as it stands and don't want to change it
Often, client components use HTTP to communicate with the server, butany other suitable protocol may be used as long as both client and servertiers support the protocol Any number of communication methods can beused, from straight web-based (D/X) HTML for browsers, to WML for cellphones, to XML for applet/application or other clients, or serialized Javaobjects between Java-based applets or applications
Java-based clients in J2EE applications will use a thin client structure,
which means that a relatively lightweight client application communicateswith the server The server has the more complex and heavyweight
responsibilities, such as connecting to one or more databases,
connecting to other 'legacy' applications, providing other services
(messaging, say), and any other processing of complex business logic.This is generally considered most efficient, as J2EE servers contain thewider range of services (which do not then have to be downloaded to theclient) and are designed to be secure, fast and reliable
Trang 38Application Container
The application container (provided by J2SE) runs the Java applicationfrom the client machine and normally uses the Swing (and/or AbstractWindow Toolkit (AWT)) APIs to construct the graphical user interface.The diagram below shows the containers and a sample application:
The application, as shown in the diagram above, is packaged in a JARfile As expected, the application is executed from the main() method inthe application class The JAR file also includes any other classes orpackages required by the application, and may also include (though notincluded in the J2EE specifications) any resource files, such as imagesthat may be required The application container will provide access to theentire standard API included with J2SE and may provide additional
services The application may have access to all components that exist
on the middle tier including servlets, JSP pages and EJBs
Generally though, the application will connect to the middle tier to sendrequests and receive responses Normally the client is fully responsiblefor initiating requests, although the JMS (Java Message Service) API can
be used to listen for event or message notification from the middle tier.The application container provides the client application with the runtimeenvironment and access to the libraries of the Java 2 Platform, StandardEdition
Applet Container
Trang 39executed The applet is also limited to only contacting the server fromwhich it was downloaded
Middle Tier Containers
There are two containers that can be found on a J2EE application server,and these contain components from the middle tier: either web
components or EJB components Let's take a closer look at them
The Web Container
A web container is a Java environment that manages the execution of allservlets and JavaServer Pages (JSP) (both of which are web
components) for a web application It is part of a web or application
server that supplies the network services over which requests and
responses are made It must support HTTP, and optionally may supportother protocols It may be built into a web server or may be plugged in as
The EJB Container
Enterprise JavaBeans (EJB) are business components that contain the
business rules or logic There are two basic types of EJBs Session
beans are logic-orientated and deal with handling client requests (oftenfrom servlets) on one hand and the data processing logic on the other
Trang 40EJBs are run in an EJB container EJB components are reusable and aredesigned to be pooled and efficiently recycled for optimization It is theEJB container's responsibility to manage the execution and pooling ofEJBs for the application