Table Of ContentJava(cid:228) Servlet Programming
Exploring Java(cid:228)
Java(cid:228) Threads
Java(cid:228) Network Programming
Java(cid:228) Virtual Machine
Java(cid:228) AWT Reference
Java(cid:228) Language Reference
Java(cid:228) Fundamental Classes Reference
Database Programming with JDBC(cid:228) and Java(cid:228)
Java(cid:228) Distributed Computing
Developing Java Beans(cid:228)
Java(cid:228) Security
Java(cid:228) Cryptography
Java(cid:228) Swing
Java(cid:228) Servlet Programming
Also from O’Reilly
Java(cid:228) in a Nutshell
Java(cid:228) in a Nutshell, Deluxe Edition
Java(cid:228) Examples in a Nutshell
Java(cid:228) Servlet Programming
Jason Hunter
with William Crawford
Beijing• Cambridge• Farnham• Köln• Paris• Sebastopol• Taipei• Tokyo
Java ™Servlet Programming
by Jason Hunter with William Crawford
Copyright © 1998 O’Reilly & Associates, Inc. All rights reserved.
Printed in the United States of America.
Published by O’Reilly & Associates, Inc., 101 Morris Street, Sebastopol, CA 95472.
Editor: Paula Ferguson
Production Editor: Paula Carroll
Editorial and Production Services: Benchmark Productions, Inc.
Printing History:
October 1998: First Edition
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered
trademarksandTheJava™SeriesisatrademarkofO’Reilly&Associates,Inc.Theassociation
oftheimageofacopperteakettle withthetopicofJava™Servletprogrammingisatrademark
of O’Reilly & Associates, Inc. Java™ and all Java-based trademarks and logos are trademarks
orregisteredtrademarksofSunMicrosystems,Inc.,intheUnitedStatesandothercountries.
O’Reilly & Associates, Inc. is independent of Sun Microsystems.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsare
claimed as trademarks. Where those designations appear in this book, and O’Reilly &
Associates, Inc. was aware of a trademark claim, the designations have been printed in caps
or initial caps.
Whileeveryprecautionhasbeentakeninthepreparationofthisbook,thepublisherassumes
no responsibility for errors or omissions, or for damages resulting from the use of the
information contained herein.
ISBN: 1-56592-391-X [1/00]
[M]
opd
Table of Contents
0: 0:
Preface .............................................................................................................................ix
1. Introduction .....................................................................................................1
History of Web Applications ...............................................................................1
Support for Servlets .............................................................................................7
The Power of Servlets ........................................................................................10
2. HTTP Servlet Basics...................................................................................14
HTTP Basics .......................................................................................................14
The Servlet API ..................................................................................................17
Page Generation ................................................................................................19
Server-Side Includes ..........................................................................................27
Servlet Chaining and Filters .............................................................................30
JavaServer Pages.................................................................................................37
Moving On .........................................................................................................46
3. The Servlet Life Cycle ................................................................................48
The Servlet Alternative......................................................................................48
Servlet Reloading...............................................................................................55
Init and Destroy .................................................................................................56
Single-Thread Model.........................................................................................62
Background Processing.....................................................................................64
Last Modified Times..........................................................................................67
v
Java™ Servlet Programming, eMatter Edition
Copyright © 2000 O’Reilly & Associates, Inc. All rights reserved.
vi TABLEOFCONTENTS
4. Retrieving Information ..............................................................................70
Initialization Parameters ...................................................................................72
The Server ..........................................................................................................74
The Client ..........................................................................................................79
The Request .......................................................................................................84
5. Sending HTML Information ..................................................................124
The Structure of a Response ..........................................................................124
Sending a Normal Response ..........................................................................125
Using Persistent Connections ........................................................................127
HTML Generation ..........................................................................................129
Status Codes .....................................................................................................142
HTTP Headers .................................................................................................145
When Things Go Wrong .................................................................................151
6. Sending Multimedia Content ................................................................159
Images...............................................................................................................159
Compressed Content.......................................................................................188
Server Push.......................................................................................................191
7. Session Tracking ........................................................................................195
User Authorization ..........................................................................................196
Hidden Form Fields ........................................................................................197
URL Rewriting .................................................................................................200
Persistent Cookies............................................................................................202
The Session Tracking API...............................................................................206
8. Security ..........................................................................................................221
HTTP Authentication .....................................................................................222
Digital Certificates ...........................................................................................232
Secure Sockets Layer (SSL) ............................................................................234
Running Servlets Securely ..............................................................................237
9. Database Connectivity .............................................................................242
Relational Databases .......................................................................................243
The JDBC API ..................................................................................................246
Java™ Servlet Programming, eMatter Edition
Copyright © 2000 O’Reilly & Associates, Inc. All rights reserved.
TABLEOFCONTENTS vii
Reusing Database Objects...............................................................................259
Transactions .....................................................................................................261
Advanced JDBC Techniques ..........................................................................272
10. Applet-Servlet Communication ............................................................277
Communication Options ................................................................................277
Daytime Server .................................................................................................284
Chat Server .......................................................................................................317
11. Interservlet Communication..................................................................337
Servlet Manipulation .......................................................................................337
Servlet Reuse ....................................................................................................342
Servlet Collaboration ......................................................................................349
Recap ................................................................................................................363
12. Internationalization .................................................................................365
Western European Languages .......................................................................366
Conforming to Local Customs .......................................................................369
Non-Western European Languages ...............................................................371
Multiple Languages .........................................................................................376
Dynamic Language Negotiation ....................................................................379
HTML Forms ...................................................................................................389
Receiving Multilingual Input .........................................................................395
13. Odds and Ends ............................................................................................397
Parsing Parameters ..........................................................................................397
Sending Email..................................................................................................401
Using Regular Expressions .............................................................................404
Executing Programs ........................................................................................407
Using Native Methods .....................................................................................412
Acting as an RMI Client ..................................................................................413
Debugging ........................................................................................................415
Performance Tuning .......................................................................................423
Java™ Servlet Programming, eMatter Edition
Copyright © 2000 O’Reilly & Associates, Inc. All rights reserved.
viii TABLEOFCONTENTS
A. Servlet API Quick Reference..................................................................425
B. HTTP Servlet API Quick Reference ....................................................447
C. HTTP Status Codes ...................................................................................472
D. Character Entities .....................................................................................478
E. Charsets .........................................................................................................484
Index .............................................................................................................................487
Java™ Servlet Programming, eMatter Edition
Copyright © 2000 O’Reilly & Associates, Inc. All rights reserved.
Preface
0. 0:
In late 1996, Java on the server side was coming on strong. Several major software
vendorsweremarketing technologies specifically aimedathelpingserver-sideJava
developers do their jobs more efficiently. Most of these products provided a pre
built infrastructure that could lift the developer’s attention from the raw socket
level into the more productive application level. For example, Netscape intro-
ducedsomethingitnamed“server-sideapplets”;theWorldWideWebConsortium
included extensible modules called “resources” with its Java-based Jigsaw web
server; and with its WebSite server, O’Reilly Software promoted the use of a tech-
nology it (only coincidentally) dubbed “servlets.” The drawback: each of these
technologies was tied to a particular server and designed for very specific tasks.
Then, in early 1997, JavaSoft (a company that has since been reintegrated into Sun
Microsystems as the Java Software division) finalized Java servlets. This action
consolidated the scattered technologies into a single, standard, generic mecha-
nismfordevelopingmodularserver-sideJavacode.Servletsweredesignedtowork
with both Java-based and non-Java-based servers. Support for servlets has since
been implemented in nearly every web server, from Apache to Zeus, and in many
non-web servers as well.
Servlets have been quick to gain acceptance because, unlike many new technolo-
gies that must first explain the problem or task they were created to solve, servlets
areaclearsolutiontoawell-recognizedandwidespreadneed:generatingdynamic
web content. From corporations down to individual web programmers, people
whostruggledwiththemaintenanceandperformanceproblemsofCGI-basedweb
programming are turning to servlets for their power, portability, and efficiency.
Others, who were perhaps intimidated by CGI programming’s apparent reliance
on manual HTTP communication and the Perl and C languages, are looking to
servlets as a manageable first step into the world of web programming.
ix
Java™ Servlet Programming, eMatter Edition
Copyright © 2000 O’Reilly & Associates, Inc. All rights reserved.
x PREFACE
This book explains everything you need to know about Java servlet programming.
The first five chapters cover the basics: what servlets are, what they do, and how
they work. The following eight chapters are where the true meat is—they explore
thethingsyouarelikelytodowithservlets.You’llfindnumerousexamples,several
suggestions,afewwarnings,andevenacoupleoftruehacksthatsomehowmadeit
past technical review.
We cover Version 2.0 of the Servlet API, which was introduced as part of the Java
Web Server 1.1 in December 1997 and clarified by the release of the Java Servlet
DevelopmentKit2.0inApril1998.ChangesintheAPIfromVersion1.0,finalized
in June 1997, are noted throughout the text.
Audience
Is this book for you? It is if you’re interested in extending the functionality of a
server—such as extending a web server to generate dynamic content. Specifically,
this book was written to help:
CGI programmers
CGI is a popular but somewhat crude method of extending the functionality
of a web server. Servlets provide an elegant, efficient alternative.
NSAPI, ISAPI, ASP, and Server-Side JavaScript programmers
EachofthesetechnologiescanbeusedasaCGIalternative,buteachhaslimi-
tations regarding portability, security, and/or performance. Servlets tend to
excel in each of these areas.
Java applet programmers
It has always been difficult for an applet to talk to a server. Servlets make it
easier by giving the applet an easy-to-connect-to, Java-based agent on the
server.
Authors of web pages with server-side includes
Pages that use server-side includes to call CGI programs can use <SERVLET>
tags to add content more efficiently to a page.
Authors of web pages with different appearances
Bythiswemeanpagesthatmustbeavailableindifferentlanguages,havetobe
converted for transmission over a low-bandwidth connection, or need to be
modified in some manner before they are sent to the client. Servlets provide
something called servlet chaining that can be used for processing of this type.
Each servlet in a servlet chain knows how to catch, process, and return a
specific kind of content. Thus, servlets can be linked together to do language
translation, change large color images to small black-and-white ones, convert
imagesinesotericformatstostandardGIForJPEGimages,ornearlyanything
else you can think of.
Java™ Servlet Programming, eMatter Edition
Copyright © 2000 O’Reilly & Associates, Inc. All rights reserved.