584
Web Development with JavaServer Pages

(Manning)---Web Development with JavaServer Pages---(2000).pdf

Embed Size (px)

Citation preview

  • Web Development with JavaServer Pages

    jsp.book Page 1 Friday, March 17, 2000 2:32 PM

  • jsp.book Page 2 Friday, March 17, 2000 2:32 PM

  • jsp.book Page 3 Friday, March 17, 2000 2:32 PMWeb Development with

    JavaServer PagesDUANE K. FIELDS

    MARK A. KOLBMANN INGGreenwich

    (74 w. long.)

  • For online information and ordering of this and other Manning books, go to www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact:

    Special Sales DepartmentManning Publications Co.32G

    2000 b

    No part in any fowritten p

    Many ofclaimed Publicaticaps or a

    Recognizbooks we

    Library o

    M3G

    Printed i1 2 3 4

    jsp.book Page 4 Friday, March 17, 2000 2:32 PM Lafayette Place Fax: (203) 661-9018reenwich, CT 06830 email: [email protected]

    y Manning Publications Co. All rights reserved.

    of this publication may be reproduced, stored in a retrieval system, or transmitted, rm or by means electronic, mechanical, photocopying, or otherwise, without prior ermission of the publisher.

    the designations used by manufacturers and sellers to distinguish their products are as trademarks. Where those designations appear in the book, and Manning ons was aware of a trademark claim, the designations have been printed in initial ll caps.

    ing the importance of preserving what has been written, it is Mannings policy to have the publish printed on acid-free paper, and we exert our best efforts to that end.

    f Congress Cataloging-in-Publication Data

    anning Publications Co. Copyeditor: Elizabeth Martin2 Lafayette Place Typesetter: Tony Robertsreenwich, CT 06830 Cover designer: Leslie Haimes

    n the United States of America5 6 7 8 9 10 CM 03 02 01 00

  • jsp.book Page 5 Friday, March 17, 2000 2:32 PM

    To Krisfor her patience, encouragement

    and good humor that made this project possible. D.K.F.

    For Megan, Andrew, and Jean

    your presence is my strength, and your love my inspiration. M.A.K.

  • jsp.book Page 6 Friday, March 17, 2000 2:32 PM

  • jsp.book Page vii Friday, March 17, 2000 2:32 PM1 Introduction 12 Fundamentals 213 Programming JSP scripts 49

    4 Actions and implicit objects 845 Using JSP components 1116 Developing JSP components 1477 Working with databases 1788 Architecting JSP applications 209

    brief contents9 An example JSP project 250

    10 Deploying JSP applications 29711 Performing common JSP tasks 32112 JSP by example 36613 Creating custom tags 40314 Implementing advanced custom tags 436

  • viii BRIEF CONTENTS

    A Running the reference implementation 477

    jsp.book Page viii Friday, March 17, 2000 2:32 PMB Incorporating Java applets 489C JSP resources 503D JSP syntax reference 508E JSP API reference 524

    index 545

  • jsp.book Page ix Friday, March 17, 2000 2:32 PMpreface xixacknowledgments xxiabout this book xxiiiabout the authors xxviiauthor online xxviiiabout the cover illustration xxix

    1 Introduction 11.1 What is JSP? 21.2 Evolution of dynamic content technologies 2

    Common Gateway Interface 3 ColdFusion 5Active Server Pages 6 Server-Side JavaScript 6

    contentsPHP 7 Java servlets 7 JavaServer Pages 9

    1.3 JSP and Java 2 Enterprise Edition 10Java platform editions 11 Web-based applications 11

    1.4 JSP benefits 13Performance 13 Reusable components 16Separating presentation and implementation 17Achieving division of labor 19

  • x CONTENTS

    Fundamentals 21

    jsp.book Page x Friday, March 17, 2000 2:32 PM2 2.1 Writing your first JSP 22About the examples 22 Hello, World! 22Hello, World! revisited 23 Hello, World! the Bean edition 25 Hello Real World 27

    2.2 Tag conventions 28Scripting-oriented tags 29 XML-based tags 29

    2.3 Running JSP 31Adding JSP support 32 How JSPs work 33Buffered output 38 Session management 40Scalability 43 Error handling 46

    3 Programming JSP scripts 493.1 Scripting languages 503.2 JSP tags 52

    3.3 JSP directives 52Page directive 52 Include directive 63Tag library directive 65

    3.4 Scripting elements 67Declarations 67 Expressions 71 Scriptlets 74

    3.5 Flow of control 76Conditionalization 76 Iteration 77 Exception handling 77 A word of caution 80

    3.6 Comments 81Content comments 81 JSP comments 81Scripting language comments 82

  • CONTENTS xi

    Actions and implicit objects 84

    jsp.book Page xi Friday, March 17, 2000 2:32 PM4 4.1 Implicit objects 85Servlet-related objects 87 Input/Output 88Contextual objects 95 Error handling 103

    4.2 Actions 104Forward 104 Include 108 Plug-in 110Bean tags 110

    5 Using JSP components 1115.1 The JSP component model 112Component architectures 112 Benefits of a component architecture 112 Component design for web projects 114 Building applictions from components 115

    5.2 JavaBean fundamentals 117The different types of JavaBeans 120

    5.2 JSP Bean tags 122Tag-based component programming 122 Accessing JSP components 124 Initializing Beans 132Controlling a Beans scope 139

    6 Developing JSP components 1476.1 What makes a Bean a Bean? 148Bean conventions 148 The Bean constructor 149Defining a Beans properties 150 Indexed properties 154 Boolean properties 158JSP type conversion 159 Configuring Beans 161

    6.2 Some Examples 162Example: a TimerBean 162A Bean that calculates interest 165

  • xii CONTENTS

    6.3 Bean interfaces 169The BeanInfo interface 169 The Serializable

    jsp.book Page xii Friday, March 17, 2000 2:32 PMinterface 170 The HttpSessionBindingListener interface 171 Other features of the Bean API 172

    6.4 Mixing scriptlets and Bean tags 173Accessing Beans through scriptlets 173Accessing scriptlet created objects 173

    7 Working with databases 1787.1 JSP and JDBC 179JNDI and data sources 180 Prepared statements 181

    7.2 Database driven JSPs 182Creating JSP components from table data 182JSPs and JDBC data types 185 Maintaining persistent connections 188 Handling large sets of results 191Transaction processing 196

    7.3 Example: JSP conference booking tool 197Project overview 198 Our database 198Design overview 198

    8 Architecting JSP applications 2098.1 Web applications 210Web application flow 212Architectural approaches 213

    8.2 Page Centric Design 213Role-based pages 213 Building composite pages 216Limitations of the page-centric approach 218

  • CONTENTS xiii

    8.3 Servlet-centric design 219Hello, Worldwith servlets 220 JSP and the servlet

    jsp.book Page xiii Friday, March 17, 2000 2:32 PMAPI 221 Servlets for application control 224 Servlets for handling application logic 225 Servlets as single entry points 226 Handling errors in the servlet 230Example: servlet-centric employee browser 230EmployeeBean 232 FetchEmployeeServlet 235JSP employee list 238 JSP page viewer 239

    8.4 Enterprise JavaBeans 241What are Enterprise JavaBeans? 241 JavaBeans vs. EJBs 241 Application servers and EJB containers 242Application design with EJBs 243

    8.5 Choosing an appropriate architecture 244Application environment 244 Enterprise software requirements 246 Performance, scalability, and availability 246 Technical considerations 247Organizational considerations 248

    9 An example JSP project 2509.1 Introduction 251Project motivations 251 Application requirements 251Application modules 253 Building a FAQ component 254

    9.2 The storage module 256Database schema 257 The FaqRepository class 257Storage module exceptions 263

    9.3 The administration module 264The administration servlet 265 The main menu 272Adding an FAQ 275 Deleting an FAQ 279Updating an FAQ 285

  • xiv CONTENTS

    9.4 The web access module 290The FaqServlet 290 Viewing a single FAQ 292

    jsp.book Page xiv Friday, March 17, 2000 2:32 PMViewing all the FAQs 293 A table of contents view 294Plain text view 296

    10 Deploying JSP applications 29710.1 This means WAR 298WAR is XML 299 Waging WAR 301

    10.2 The art of WAR 302WAR materiel 303Drafting deployment descriptors 307

    10.3 Maintaining a WAR footing 319

    11 Performing common JSP tasks 32111.1 Handling cookies 322Managing cookies 322 The Cookie class 323Example 1: setting a cookie 324Example 2: retrieving a cookie 326

    11.2 Creating error pages 329An erroneous page 330 Data collection methods 330Sending electronic mail 335 The error page 337

    11.3 Mixing JSP and JavaScript 340

    11.4 Building interactive interfaces 344Sticky widgets 344 Utility methods 345 The example form 347 Setting up the form 349 Text and hidden fields 349 Text areas 350 Radio buttons 350Select boxes 351 Check boxes 352 Form source 352

    11.5 Validating form data 354Client- and server-side validation 355Example: server-side validation 356

  • CONTENTS xv

    11.6 Miscellaneous tasks 361Determining the last modification date 362

    jsp.book Page xv Friday, March 17, 2000 2:32 PMExecuting system commands 363Generating XML 364

    12 JSP by example 36612.1 A rotating banner ad 367The BannerBean 367 Using the Bean 368

    12.2 A random quote generator 370The QuoteBean 370 Using the Bean 371

    12.3 The Tell a Friend! sticker 372The sticker 373 The MailForm page 375Sending the mail 376

    12.4 A JSP Whois client 378The Whois protocol 378 Requirements and design considerations 380 The WhoisBean 380Building the front end 388

    12.5 An index generator 391A basic implementation 391 An improved version 394Going further 398

    12.6 A button to view JSP source 398Displaying the source 399 Limitations of the view source program 401 Adding a view source button to a page 401 Viewing source through a bookmark 401

    13 Creating custom tags 40313.1 Role of custom tags 40413.2 How tag libraries work 405

  • xvi CONTENTS

    13.3 Tag library descriptors 408

    Library elements 409 Tag elements 410

    jsp.book Page xvi Friday, March 17, 2000 2:32 PMAttribute elements 411

    13.4 API overview 412Tag handlers 412 Helper classes 416Auxiliary classes 418

    13.5 Example tag library 419

    13.6 Content substitution 420

    13.7 Tag attributes 422

    13.8 Content translation 427URL rewriting 427 HTML encoding 431

    13.9 To be continued 435

    14 Implementing advanced custom tags 43614.1 Interacting tags 437Interaction mechanisms 437 Outlining tags 439

    14.2 Flow of control 449Conditionalization 450 Iteration 458

    14.3 Packaging the tag library 475

    14.4 For further information 476

    A Running the reference implementation 477A.1 Prerequisites 478A.2 Installation 478

    A.3 Constructing an application 485

    B Incorporating Java applets 489B.1 Browser support for Java 2 489B.2 The plug-in action 491

    B.3 Example: applet configuration 496

  • CONTENTS xvii

    JSP resources 503

    jsp.book Page xvii Friday, March 17, 2000 2:32 PMC C.1 Java implementations 503C.2 JSP-related web sites 504

    C.3 JSP FAQs and tutorials 504

    C.4 JSP containers 505

    C.5 Java application servers with JSP support 505

    C.6 JSP development tools 506

    C.7 Tools for performance testing 506

    C.8 Mailing lists and newsgroups 507

    D JSP syntax reference 508D.1 Content comments 508D.2 JSP comments 509

    D.3 510

    D.4 511

    D.5 512

    D.6 513

    D.7 514

    D.8 515

    D.9 516

    D.10 517

    D.11 518

    D.12 520

    D.13 521

    D.14 522

  • JSP API reference 524

    jsp.book Page xviii Friday, March 17, 2000 2:32 PME E.1 JSP Implicit Objects 525E.2 Package javax.servlet 525

    E.3 Package javax.servlet.http 530

    E.4 Package javax.servlet.jsp 535

    E.5 Package javax.servlet.jsp.tagext 539

    index 545

  • jsp.book Page xix Friday, March 17, 2000 2:32 PMprefaceIn late 1998 we were asked to develop the architecture for a new website. Ouremployer, a vendor of enterprise software for system and network management,had an unconventional set of requirements: that the site be able to provide productsupport data customized for each customer; and that the support data be tailoredto the software the customer had already purchased, as well as the configurationsalready selected.

    Of course, the website needed to look sharp and be easy to navigate. Manage-ment software, which of necessity must be flexible and support a wide range ofoperating conditions, tends to be very complex. This particular software was tar-geted at Internet and electronic commerce applications, so using the web as a majorcomponent of product support was a natural fit. By personalizing web-based sup-port for each customer, this inherent complexity would be reduced, and the cus-tomer experience improved. But how to accomplish that ... and how to do it withinthe time constraints the project required?

    What we needed was an architecture that would give everyone on the team,both the designers and the programmers, as much freedom as possible to workunhindered in the limited time available. The ability of these two groups to

    progress independently, without costly rework, was crucial. A solution that couldprovide dynamic content as an add-on to otherwise conventional HTML files clearlywas the best approach. We briefly considered, then just as quickly dismissed, thenotion of building our own dynamic context system. There just wasnt enough timeto deliver both a publishing system and a website.

  • xx PREFACE

    At the time we were already familiar with Java servlets. Indeed, servlets were akey element of the architecture of the product to which this site would be devoted.

    jsp.book Page xx Friday, March 17, 2000 2:32 PMWe mulled over using servlets for the site itself but were concerned with how thiswould affect those responsible for the content, graphics, and layout of the site.

    As we researched the problem further we were reminded of an ongoing initiativeat Sun Microsystems called JavaServer Pages (JSP). JSP was still being refined, andVersion 1.0 was months away. However, it was intended to become a standard Javatechnology, and it used Java servlets as its foundation. It also allowed us to imple-ment dynamic content on top of standard HTML files. Best of all, it worked! As webecame more familiar with JSP, we found that it worked very well indeed.

    As is often the case, there were some rough spots as the JSP specification wentthrough major changes along the way. Hair was pulled, teeth were gnashed, les-sons were learned. Fortunately, we obtained a great deal of help from the JSP com-munitythe developers at Sun and the other JSP vendors, as well as our fellowearly adopters.

    This book thus serves a twofold purpose. First, we hope to help future users ofJSP by sharing the hard-earned lessons of our experience. We offer them what wehope is a helpful guide to the current JSP feature set: JavaServer Pages is now at ver-sion 1.1 and the need for published reference material has long been recognized.

    Second, we offer this book as an expression of gratitude to the current commu-nity of JSP developers in return for the assistance they provided when we needed it.Thanks to all.

  • jsp.book Page xxi Friday, March 17, 2000 2:32 PMacknowledgmentsWe recognize the support and understanding of the many people who helped makethis book possible. We acknowledge:

    T. Preston Gregg, our development manager, for allowing us to make the earlyleap to a JSP architecture, before the technology was considered ready for primetime. This head start was painful at times, but ultimately proved a boon to our webdevelopment projects. It also gave us the experience necessary to develop this text,for which we are equally grateful. Other colleagues who advised us during the writ-ing of the this book include Kirk Drummond and Ward Harold.

    The JSP design team at Sun Microsystems, especially Eduardo Pelegr-Llopart. Hisassistance and attentiveness to our queries was critical to the success of this effort.

    The teeming millions of Java and JSP developers who continue to offer theirinsights and expertise to the development community through their unselfish par-ticipation in mailing lists, newsgroups, and the web. Double thanks to everyoneparticipating in the Jakarta and Apache projects for their outstanding work in theOpen Source arena. You are all instrumental to the continuing success of Java andestablishing it as a lingua franca for Internet development.

    Our publisher, Marjan Bace, for giving us this opportunity, and our editor, Eliza-

    beth Martin, for her yeomans effort in polishing this manuscript. Their insightsand guidance were invaluable to the completion of this book.

    Our reviewers, whose comments, criticisms, and commendations throughout thedevelopment of this book advised, corrected, and encouraged us. Our deep appreci-ation is extended to Michael Andreano, Ruslan Belkin, Drew Cox, Jose Luis Diaz,Sergio Queijo Diaz, Richard Friedman, Dennis Hoer, Paul Holser, Vimal Kansal,

  • xxii ACKNOWLEDGMENTS

    Sachin Khanna, Daniel Kirkdorffer, JJ Kuslich, Eric Lunt, Dave Miller, VincentPartington, Harold Sasaki, Edward Toupin, Wong Kok Wai, and Paul Williamson.

    jsp.book Page xxii Friday, March 17, 2000 2:32 PMWe are also indebted to Ted Kennedy, our review editor, for coordinating thisimposing task.

    Our friends, families, and coworkers for their unfailing support, assistance, andtolerance throughout the writing process. Without them this book could not havebeen possible.

  • jsp.book Page xxiii Friday, March 17, 2000 2:32 PMabout this bookJavaServer Pages is a technology that serves two different communities of develop-ers. Page designers use JSP technology to add powerful dynamic content capabilitiesto web sites and online applications. Java programmers write the code that imple-ments those capabilities behind the scenes.

    Web Development with JavaServer Pages is intended to present this technology toboth groups. It is impossible in a book of this length to provide all the backgroundinformation required by this subject, and, for this reason, we do not attempt todescribe the HTML markup language. It is assumed that the reader is sufficientlyfamiliar with HTML to follow the examples presented. It is likewise assumed thatthe reader is familiar with URLs, document hierarchies, and other concepts relatedto the design, operation, and management of web servers.

    We also do not include a primer on the Java programming language. As withHTML, there is a wealth of reference information available on the language itself.Our focus here is strictly on JavaServer Pages. Obviously, JSP interacts strongly withJava and HTML, as well as other technologies such as HTTP servers and databases.The interactions between JSP and these technologies will be covered in depth, butthe details of these related technologies are beyond the scope of this book. What, then, can the reader expect to be covered in this book? Chapter 1 answers the question, what is JSP and how did the technology evolve?

    This chapter is an overview of how this new technology can be used to add dynamiccontent to web pages, and the benefits it provides compared to other dynamic con-tent systems.

  • xxiv ABOUT THIS BOOK

    Chapter 2 presents introductory examples, as well as an overview of the basicconventions for JSP tags. This is followed by a discussion of how JSP interacts with

    jsp.book Page xxiv Friday, March 17, 2000 2:32 PMthe web server and the end users browser, and how JSP pages actually work to pro-duce dynamic content. As it covers all of the major aspects of JSP technology at ahigh level, this chapter is geared toward both Java programmers and page designers.

    Chapters 3 and 4 introduce the four basic categories of JSP tags: directives,scripting elements, comments, and actions. The use and syntax of all standard JSPtags is presented, with the exception of those specific to JavaBeans. The first threecategories are covered in chapter 3.

    Chapter 4 introduces action tags, and describes the implicit Java objects accessi-ble from all JSP pages. In both of these chapters, particular emphasis is placed on theapplication of these tags and objects to dynamic content generation via scripting.The scripting examples use the Java programming language, and may be of second-ary interest to page designers. Because this chapter introduces most of the majorfunctionality provided by JavaServer Pages, it is intended for a general audience.

    Chapters 5 and 6 cover JSPs component-centric approach to dynamic pagedesign through the use of JavaBeans and JSP Bean tags. The JSP tags covered inchapter 5 allow page designers to interact with Java components through HTML-like tags, rather than through Java code. This chapter will introduce the JavaBeanscomponent model, and demonstrate JSPs interaction with JavaBeans through theuse of the JSP Bean tags.

    Chapter 6 builds on this foundation, teaching Java programmers how to developtheir own JavaBeans for use with JSP.

    Chapter 7, geared primarily toward Java developers, covers techniques for work-ing with databases through JSP. Nowadays, most large-scale web sites employ data-bases for at least some portion of their content. Ad management, user registrationinformation, inventory records, and community services are all quite commonlyhandled through a database. JSP and relational databases make a good combination.The relational database gives us the organizational capabilities and the performancenecessary to manage dynamic data. By combining the power of a relational databasewith the flexibility of JSP for content presentation and front-end design, it is practi-cal to build rich, interactive interfaces to your data.

    In chapter 8, we discuss several architectural models useful for developing JSPapplications. We examine the various architectural options available when we com-bine JSP pages with servlets, Enterprise JavaBeans, HTML, and other software ele-ments to create web-based applications. The introductory material in this chapter,as well as the final section on selecting an architecture, are geared toward a general

  • ABOUT THIS BOOK xxv

    audience. The bulk of this chapter, which focuses on how these architectural modelsare implemented, is geared toward Java programmers.

    jsp.book Page xxv Friday, March 17, 2000 2:32 PM In chapter 9, we apply the JSP programming techniques we covered in previouschapters to the development of a real world, enterprise web application. In achapter-length example, we will be developing a system for managing and present-ing lists of frequently asked questions (FAQs). This chapter is based on a projectthe authors recently completed for a major software companys customer supportsite. The presentation aspect of this chapter should be of interest to page designers,while the implementation aspects should be of interest to programmers.

    Whatever architecture you have selected for your JSP development, an applica-tion isnt useful until it is successfully deployed. The JSP and servlet specificationshave introduced several new facilities for easing and improving the deployment ofJava-based web applications. Chapter 10 explains Suns new Web Archive formatand how it can be used to create packaged JSP applications. Since both code andpages are stored together in a packaged application, this chapter should be of inter-est to all JSP developers.

    In chapters 11 and 12 we present a number of examples of JSP programming,which should be of interest to both page designers and programmers. The examplesof form management, interface design, and error handling in chapter 11 have beendesigned to be representative of common tasks for which you might employ JSP.Chapter 12 focuses on full-fledged applications that illustrate the various techniquesand practices presented in the other chapters of this book.

    Chapter 13 covers the development, deployment, and use of custom tag librar-ies. This material focuses primarily on the implementation of custom tags by Javaprogrammers. From the perspective of jointly designing a set of application-specifictags, page designers may find some benefit in reviewing the introductory sections ofthis chapter, which discuss the types of functionality that can be provided by customJSP tags. In chapter 14, we expand upon the topic of custom tags with additionalexamples that take advantage of more advanced features of Java and JSP.

    There are five appendices in this book. Appendix A provides instructions forinstalling and running Tomcat, the free reference implementation for both servletsand JavaServer Pages jointly developed by Sun Microsystems and the Apache Soft-ware Foundation. Tomcat provides an Open Source, zero-cost platform for JSPdevelopment that is fully compliant with the published specifications. This chapterassumes no programming knowledge, but does require familiarity with the operat-ing system on which the software is to be installed.

  • xxvi ABOUT THIS BOOK

    Java applets are small applications that run within the context of a web browser.Appendix B describes the action, a cross-platform tag for specifying

    jsp.book Page xxvi Friday, March 17, 2000 2:32 PMapplets which use Sun Microsystems Java Plug-in technology in order to takeadvantage of the Java 2 platform within the browser. This appendix is directed atJava programmers.

    As is the case with any major software technology in use today, there is a wealthof information on JSP and related topics available online. Appendix C provides a list-ing of mailing lists, newsgroups, and web sites of relevance to both categories of JSPdevelopers, accompanied by brief descriptions of the content available from each.

    Appendix D, serving as a quick reference, summarizes the use and syntax of thestandard (i.e., built-in) JSP tags available to page designers.

    Appendix E, geared toward Java programmers, lists all of the Java classes intro-duced by the JSP and servlet specifications to supplement the standard Java classlibrary for web-based application development. Summary descriptions of theseclasses and their methods are provided, as is a table of the JSP implicit objects.

    Source code

    The source code for all of the examples called out as listings in the book is freelyavailable from our publishers web site, www.manning.com/fields, and from thebooks companion web site, www.taglib.com. The listings are organized by chapterand topic and include the source for both Java classes and JSP pages used in theexamples. If any errors are discovered updates will be made available on the web.

    Code conventions

    Courier typeface is used to denote code (JSP, Java, and HTML) as well as filenames,variables, Java class names, and other identifiers. When JSP is interspersed withHTML, we have used a bold Courier font for JSP elements in order to improve thereadability of the code. Italics are used to indicate definitions and user specified val-ues in syntax listings.

  • jsp.book Page xxvii Friday, March 17, 2000 2:32 PMabout the authorsDUANE K. FIELDS, web applications developer and Internet technologist, has anextensive background in the design and development of leading edge Internetapplications for companies such as IBM and Netscape Communications. Duanelives in Austin, Texas, where he consults, does Java applications development, andtries to find more time to fish. He frequently speaks at industry conferences andother events and has published numerous articles on all aspects of web applicationdevelopment from Java to relational databases. He is a Sun Certified Java Program-mer, an IBM Master Inventor, and holds an engineering degree from Texas A&MUniversity. He can be reached at his website at www.deepmagic.com.

    MARK A. KOLB, Ph.D., is a reformed rocket scientist with graduate and undergrad-uate degrees from MIT. A pioneer in the application of object-oriented modeling toaerospace preliminary design, his contributions in that field were recently recog-nized with a NASA Space Act Award. With over 15 years experience in softwaredesign, Marks current focus is on Internet applications, ranging from applet-basedHTML editors to server-side systems for online product support and fulfillment.Mark resides in Round Rock, Texas, with his family and a large stack of unread

    books hes hoping to get to now that this one is done. His home on the web is atwww.taglib.com.

  • jsp.book Page xxviii Friday, March 17, 2000 2:32 PMauthor onlinePurchase of Web Development with Java Server Pages includes free access to a privateInternet forum where you can make comments about the book, ask technical ques-tions, and receive help from the authors and other JSP users. To access the forum,point your web browser to www.manning.com/fields. There you will be able tosubscribe to the forum as well as receive information on how to access the forumonce you are registered.

  • jsp.book Page xxix Friday, March 17, 2000 2:32 PMabout the cover illustrationThe cover illustration of this book is from the 1805 edition of Sylvain Marchalsfour-volume compendium of regional dress customs. This book was first publishedin Paris in 1788, one year before the French Revolution. Its title alone required nofewer than 30 words.

    Costumes Civils actuels de tous les peuples connus dessins daprsnature gravs et coloris, accompagns dune notice historique surleurs coutumes, moeurs, religions, etc., etc., redigs par M. SylvainMarchal

    The four volumes include an annotation on the illustrations: grav la manirenoire par Mixelle daprs Desrais et colori. Clearly, the engraver and illustratordeserved no more than to be listed by their last namesafter all they were meretechnicians. The workers who colored each illustration by hand remain nameless.

    The remarkable diversity of this collection reminds us vividly of how distant andisolated the worlds towns and regions were just 200 years ago. Dress codes havechanged everywhere and the diversity by region, so rich at the time, has melted

    away. It is now hard to tell the inhabitant of one continent from another. Perhapswe have traded cultural diversity for a more varied personal lifecertainly a morevaried and interesting technological environment.

    At a time when it is hard to tell one computer book from another, Manning cel-ebrates the inventiveness and initiative of the computer business with book coversbased on the rich diversity of regional life of two centuries ago, brought back to lifeby Marchals pictures. Just think, Marchals was a world so different from ourspeople would take the time to read a book title 30 words long.

  • jsp.book Page xxx Friday, March 17, 2000 2:32 PM

  • This Ja

    T

    Tg

    Him

    jsp.book Page 1 Friday, March 17, 2000 2:32 PM chapter coversvaServer Pages technology and how it works

    he evolution of dynamic content technologies

    he benefits of using JSP for dynamic content eneration

    ow to separate presentation and plementation 1Introduction1

  • Evolution of dynamic content technologies 2

    Welcome to Web Development with JavaServer Pages. This book has been written to

    1.1

    1.2

    jsp.book Page 2 Friday, March 17, 2000 2:32 PMaddress the needs of a wide audience of web developers. You may have only recentlyheard about this exciting new technology for developing dynamic web content, orperhaps you have already begun to use JavaServer Pages in your own projects. Youmay be a HyperText Markup Language (HTML) designer with little or no back-ground in programming, or a seasoned Java architect. In any case, this book willshow you how to use JavaServer Pages to improve the look and maintainability ofdynamic web sites and web-based applications, and ease the design and develop-ment process. So, without further ado, lets begin our look at JavaServer Pages.

    What is JSP?

    JavaServer PagesJSP, for shortis a Java-based technology that simplifies theprocess of developing dynamic web sites. With JSP, web designers and developerscan quickly incorporate dynamic elements into web pages using embedded Java anda few simple markup tags. These tags provide the HTML designer with a way toaccess data and business logic stored inside Java objects without having to masterthe complexities of Java application development.

    Think of JSP as a type of server-side scripting language, although, as well seelater, it operates quite differently behind the scenes. JavaServer Pages are text files,usually with the extension .jsp, that take the place of traditional HTML pages. JSPfiles contain traditional HTML along with embedded code that allows the pagedesigner to access data from Java code running on the server. When the page isrequested by a user and processed by the HyperText Transport Protocol (HTTP)server, the HTML portion of the page is passed straight through. The code portionsof the page, however, are executed at the time the request is received, and thedynamic content generated by this code is spliced into the page before it is sent tothe user. This provides for a separation of the HTML presentation aspects of thepage from the programming logic contained in the code, a unique benefit wellconsider in detail below.

    Evolution of dynamic content technologies

    For the simplest web requests, a browser requests an HTML document, and theweb server finds the corresponding file and returns it. If the HTML documentincludes any images, the browser will in turn submit requests for the image docu-ments, as well. As described here, all of these requests are for static files. That is, thedocuments that are requested never change depending upon who requested them,

  • 3 CHAPTER 1Introduction

    when they were requested, or which (if any) additional parameters were included

    1.2.1

    jsp.book Page 3 Friday, March 17, 2000 2:32 PMwith the request. New versions of the documents might be placed on the server, butat any given time, every request for those documents returns exactly the same results.In such cases, the web server needs only to locate the file corresponding to therequested document, and respond to the web browser with the contents of that file.

    Much of the data delivered over the web today, however, is dynamic in nature.Up-to-the-minute stock prices and the latest weather reports can be viewed. Ausers personal email messages and appointment calendar can be managed. Con-sumers can add contents to that e-commerce staple, the online shopping cart, byclicking on a picture of the item they wish to buy. All of this data is transient innature, because the information it is based on is constantly changing, or because itmust be personalized for each individual viewer, or both.

    Dynamic web content, then, requires that the web server do some additionalprocessing of the corresponding request in order to generate a customizedresponse. In addition to the URL of the request, the form of this customizedresponse might be dependent upon additional parameter values included with therequest. Alternatively, it might be based on the date and time, the location on thenetwork from which the request was made, or on some representation of the iden-tity of the user making the request. Indeed, the exact details of the response mightdepend upon a combination of some or all of these factors.

    Common Gateway Interface

    The earliest HTTP servers did not include any built-in mechanisms for generatingresponses dynamically. Instead, interfaces were provided for calling other programsto translate requests into run-time content. The first standard for dynamic web con-tent was based on the Common Gateway Interface, or CGI, which specified a mech-anism for web servers to pass request information to external programs, which werethen run by the web server to generate responses at runtime. The Perl language is apopular choice for writing CGI programs, but CGI codes can be written in any lan-guage that can be called as a stand-alone program by the HTTP server. For example,a CGI program could be written in any scripting language supported by the localoperating system. Alternatively, it could be written in C and compiled into nativeobject code. CGI programs could even be written as Java applications.

    When Sun Microsystems first introduced Java technology to the computingcommunity, it was in the context of small programs, referred to as applets, whichcould be delivered over the Internet and run within web browsers. From the begin-ning, Java could also be used to write stand-alone applications, but interactive pro-grams running inside the browser certainly received most of the early attention.

  • Evolution of dynamic content technologies 4

    Nevertheless, Java-based CGI programs first appeared shortly after Java was made

    jsp.book Page 4 Friday, March 17, 2000 2:32 PMavailable to the public in 1995. It was eventually recognized that the benefits of theJava platform applied equally as well to the server as to the client, and today server-side Java plays a prominent role in the continuing evolution of the Java platform.

    The t r ad i t iona l C GIapp roach to gene r a t ingdynamic content has someinherent inefficiencies, whichultimately limit its applicabilityto large-scale deployment ofweb-based applications. Asindicated in figure 1.1, CGIprograms run outside the webserver. This means that a newprocess must be started to exe-cute a CGI program. There issome overhead associated withcreating and communicatingwith this separate process, andeach process requires its ownshare of the local machinesmemory resources. Further-mor e , C GI p r ograms a r edesigned to handle only a sin-gle request, after which they return their results to the web server and exit. Thismeans that each time a request for dynamic content is received by the web browser,it must start a new process for running the corresponding CGI program for thatspecific request, send it the request information, wait for results, then pass thoseresults back in its response to the browser. These days, it is not uncommon for pop-ular web sites to be handling thousands of simultaneous requests, so even if theinefficiencies of individual CGI program execution are fairly small, they quickly addup to significant performance penalties.

    As a result, a number of vendors have introduced new systems for dynamic gener-ation of web content. In some cases, new HTTP servers that provide built-in dynamiccontent capabilities have been introduced. Today, however, the HTTP server markethas come to be dominated by a small number of suppliers, making such all-in-oneapproaches less commercially viable. Current dynamic content systems more typicallytake the form of add-on code modules that leverage server-specific application

    Figure 1.1 Server process for running CGI programs

  • 5 CHAPTER 1Introduction

    programming interfaces (APIs) in order to interact directly with the web server pro-

    1.2.2

    jsp.book Page 5 Friday, March 17, 2000 2:32 PMcess. By plugging in as a subprocess of the web server, these systems avoid much ofthe overhead associated with conventional CGI programs, and offer dynamic con-tent capabilities with much better scalability than the traditional approach.

    As indicated earlier, dynamic content generation requires the server to processrequests at run time in order to construct an appropriate request-specific response.Instructions are required in order to perform this processing, so at one level oranother it is clear that some programming is required. As a result, many of the mostpopular dynamic content systems, such as Allaires ColdFusion, Microsofts ActiveServer Pages, Netscapes Server-Side JavaScript, and PHP (an Open Source hyper-text preprocessor) enable dynamic content to be specified using scripting languages.The use of scripting languages is a particularly appropriate choice here because webdevelopers are used to rapid turnaround when testing their web pages: as soon asthe HTML in a static web page is modified, the results of that change can be viewedin a web browser. By relying on scripting languages that do not require a lengthyedit-compile-link cycle before any code can be run, these dynamic content toolsprovide the same immediate feedback web developers have grown accustomed towith HTML.

    Similarly, in recognition of the page-centric nature of web development, thesetools enable scripts for dynamic content generation to be embedded directly in theweb pages in which the dynamic content is to appear. The static elements of thepage, governing page layout and base content, can be coded in HTML in the usualmanner. Appearing alongside this static HTML in the source document are thescripts for generating the dynamic content. When the document is requested by anend user, the web server will pass along the static HTML elements, which oftencomprise the bulk of the page, unchanged. The scripts, however, will be turnedover to the dynamic content system for execution, with the results of running thesescripts embedded into the document in place of the scripts original source code.Because the static HTML elements provide a framework into which the dynamiccontent generated by the scripts will be inserted, such tools are commonly referredto as template systems.

    ColdFusion

    The primary differences among template systems, then, lie in their scripting lan-guages, and the capabilities provided therein. ColdFusion, from Allaire, provides aset of HTML-like tags which were initially targeted at embedding database queriesinto web pages, but it has since been extended to support a wide variety of datasources for dynamic content generation. The adoption of HTML-like tags has the

  • Evolution of dynamic content technologies 6

    advantage that there is a single, consistent style of syntax throughout the page; the

    1.2.3

    1.2.4

    jsp.book Page 6 Friday, March 17, 2000 2:32 PMColdFusion tags are comfortable to web designers because they look just like theother tags present in the document. ColdFusion supports both UNIX andMicrosoft Windows platforms.

    Active Server Pages

    Microsofts Active Server Pages, often abbreviated ASP, support multiple scriptinglanguages, including PerlScript, Jscript, and VBScript. PerlScript is based on Perl,and Jscript is based on JavaScript but the default scripting language for ASP isVBScript, a subset of Microsofts popular Visual Basic programming language.VBScript includes support for accessing ActiveX components, which are compiledcode objects that can encapsulate virtually any functionality, including databaseaccess and file manipulation. A large body of commercial off-the-shelf ActiveX com-ponents is available, and Microsoft provides tools and documentation for writingyour own, as well. The major limitation of ASP, however, is that it is available onlywith Microsofts Internet Information Server (IIS), running under the WindowsNT operating system.

    NOTE As a result of its popularity, a number of vendors have developed tools for de-ploying ASP on other platforms. Chili!Soft, for example, has an ASP productfor the Apache HTTP server running on the UNIX platform, which even sup-ports interoperability between Active Server Pages and server-side Java (i.e.,servlets and JSPs). Unfortunately, ASP derives much of its power from its sup-port for ActiveX components, which, at least at the time of this writing, arenot widely available on non-Microsoft platforms.

    Server-Side JavaScript

    As you might expect, Server-Side JavaScript (SSJS) uses JavaScript as its scriptinglanguage. JavaScript is an object-oriented language (based on prototypes ratherthan classes) with a C-like syntax, but, although it has a similar name, it is not Java.SSJS is an extension of the core JavaScript language, which is also the basis for thepopular client-side JavaScript language used for scripting web browsers. SSJS addsbuilt-in features for database and email support, session management, and interop-erability with server-side Java classes using Netscapes LiveWire technology. In adeparture from the other dynamic content systems described here, SSJS is a com-piled language. A collection of web pages containing SSJS is compiled into a webapplication that is executed whenever the corresponding URLs are requested. Like

  • 7 CHAPTER 1Introduction

    compiled Java code, compiled SSJS is not platform-specific with respect to hard-

    1.2.5

    1.2.6

    jsp.book Page 7 Friday, March 17, 2000 2:32 PMware or operating system. SSJS is, however, specific to Netscapes HTTP servers(i.e., Netscape Enterprise Server and Netscape Application Server).

    PHP

    A fourth dynamic content system that is growing in popularity is PHP. PHP wasoriginally an acronym for Personal Home Page tools. As its scope and functionalityhave grown over the years, that moniker is no longer adequate and the software isnow referred to only as PHP. Like JavaScript, PHP employs a C-like syntax, and pro-vides strong support for pattern matching and database access. Extensions for com-municating with other network resources, such as mail and directory servers, arealso available. Unlike most of the other dynamic content systems now available,however, PHP is an Open Source product. As with other Open Source products,such as the Linux operating system and the Apache HTTP server, PHP is not a com-mercial product. It is instead the result of contributions from a community of inter-ested developers, freely contributing to and supporting its code base. Oneimportant result of its Open Source nature is that PHP is now available on a largenumber of platforms. PHP is compatible with Windows NT and several UNIX oper-ating systems, and with a number of HTTP servers, such as Apache, Microsofts IIS,and Netscape Enterprise Server.

    Java servlets

    In light of the importance of dynamic content generation to web developmentthen, it was natural for Sun to propose extensions to Java in this domain. In muchthe same way that Sun introduced applets as small Java-based applications for add-ing interactive functionality to web browsers, in 1996 Sun introduced servlets assmall Java-based applications for adding dynamic functionality to web servers. Javaservlets have a programming model similar to CGI scripts, insofar as they are givenan HTTP request from a web browser as input, and are expected to locate and/orconstruct the appropriate content for the servers response.

    Unlike traditional CGI programs that require spawning a new process to handleeach new request, all of the servlets associated with a web server run inside a singleprocess. This process runs a Java Virtual Machine (JVM), which is the platform-specific program for running (cross-platform) compiled Java programs. As illus-trated in figure 1.2, instead of creating a process for each request, the JVM creates aJava thread to handle each servlet request. Java threads have much less overheadthan full-blown processes, and execute within the processor memory already allo-cated by the JVM, making servlet execution considerably more efficient than CGI

  • Evolution of dynamic content technologies 8

    processing. Since the JVM persists beyond the life of a single request, servlets can

    jsp.book Page 8 Friday, March 17, 2000 2:32 PMalso avoid many time-consuming operations, such as connecting to a database, bysharing them among all requests. At the same time, because servlets are written inJava, they enjoy all the benefits of the core Java platform: an object-oriented pro-gramming model, automatic memory management, cross-platform portability, andaccess to the rich collection of Java APIs now available for accessing databases,directory servers, network resources, and so forth.

    When reduced to their essence,servlets provide a Java-based method-ology for mapping HTTP requestsinto HTTP responses. Generatingdynamic web content using servletsthen, is accomplished by means ofJava code that outputs the HTML (orother data) representing that content.In the case o f HTML data , oneapproach is for the Java code to con-struct strings containing the appropri-ate markup text and then print thosestrings on the output stream associ-ated with the HTTP response. This isoften referred to as the out.printlnapproach, because a significant por-tion of the resulting code consists oflines that start with this (or a very sim-ilar) sequence of characters.

    Another option is to take a moreobject-oriented approach to modelingthe response data, by first constructinga model of the page being constructed as a collection of Java objects. Many webpages, for example, can be modeled as a hierarchy of textual elements, including atitle, various levels of headings, and paragraphs of text providing the content for eachsection, subsection, and so on. Java classes could be defined which represent each ofthese textual elements, as well as the page itself. The classes for the textual elementswould provide methods for accessing and modifying their content. The page classwould provide methods for adding and removing textual elements. When generatingdynamic content, then, an instance of the page class is created, to which instances ofthe appropriate title, heading, and paragraph classes are then added. Once the

    Figure 1.2 Server process for running servlets

  • 9 CHAPTER 1Introduction

    complete model of the page was constructed, other methods could be called to ren-

    1.2.7

    jsp.book Page 9 Friday, March 17, 2000 2:32 PMder these objects as strings of HTML to be sent back as the servlets response. One popular library of Java classes that enables this style of dynamic content

    generation is the Element Construction Set (ECS), which, like PHP, Apache, andLinux, is an Open Source software effort. One of the key advantages of this object-oriented approach to dynamic content generation is that it lends itself to supportingmultiple forms of document output. ECS, for example, supports output in bothHTML and XML, and can be extended to support additional formats, as needed.

    In a similar manner, the Swinglets toolkit from Javelin Software allows developersto construct servlet output using a set of components modeled after those of JavasSwing library of user interface components. The Swinglets library provides severalclasses for data presentation, including tables, links, buttons, and radio buttons.Data is added to these interface components, which may then be rendered in variousformats, including HTML, Dynamic HTML, and WML (Wireless Markup Language,an HTML-like language geared toward wireless devices such as mobile phones).

    A potential disadvantage of this approach, however, is that all document con-tents, both static and dynamic, reside in program source code. As a result, anychange to such a document requires intervention by a programmer. An HTMLpage designer cannot change the layout of the page unless the associated sourcecode is changed. Indeed, any change to the static elements of the document, suchas changing the URL of a link or image, requires corresponding changes to thesource code. This dilemma also applies to the out.println approach.

    JavaServer Pages

    As discussed earlier, incorporating dynamic content must ultimately involve someform of programming to describe how that content is generated. Program code,however, tends to be expensive to create and to maintain, so minimizing the needfor programming is often a desirable goal. Combining this goal with Suns objectivefor robust, full-featured support for Java on the server, a Java-based template sys-tem, JSP, was the natural result.

    JSP is something of a hybrid among template systems, because it supports twodifferent styles for adding dynamic content to web pages. Like ASP, SSJS, and PHP,scripts can be embedded in JSP pages containing actual programming code. In thecase of JSP, this programming code is typically Java. (Actually, the JSP specificationallows for the possibility of alternative scripting languages. See chapter 3, Pro-gramming JSP scripts, for details.) Like ColdFusion, JSP supports a set of HTML-like tags that interact with Java objects on the server, without the need for raw Javacode to appear in the page. In fact, the JSP 1.1 specification takes this capability a

  • JSP and Java 2 Enterprise Edition 10

    step further, by providing a tag extension mechanism that allows developers to cre-

    1.3

    jsp.book Page 10 Friday, March 17, 2000 2:32 PMate libraries of custom tags that can be loaded into a JSP page. These custom tagscan then be used on the page just like the standard JSP tags.

    NOTE As a demonstration of the power of this approach, it is interesting to notethat Live Software, makers of the JRun servlet software, have developed a setof custom JSP tags which reproduce the tags used in Allaires ColdFusionproduct. This product, effectively a cross-platform, Java-based clone of Cold-Fusion, was released in May 1999 as . Allaire was sufficientlyimpressed by this feat that in June 1999, it bought the company.

    Servlets and JavaServer Pages first appeared as part of Suns Java Web Serverproduct, an HTTP server written in Java. Sun eventually released the servlet technol-ogy as a standard Java extension. JSP soon followed, with the first draft API specifica-tions appearing in 1998. The JavaServer Pages 1.0 Specification was released in June1999, thus ensuring a stable, well-defined platform for vendors to build against.

    Soon after Sun published the Java servlet specification, other companies beganto add support for the base servlet architecture to their products. Since JSPfunctionality itself is typically implemented using the servlet technology, other serv-let products could readily take advantage of it, and web developers quickly discov-ered its advantages.

    As such, a number of third-party products are now available for adding servletand JSP functionality to existing web servers. Two of the more popular products inthis category are JRun from Live Software and New Atlantas ServletExec. In addi-tion, in June 1999 Sun Microsystems and the Apache Software Foundationannounced the Jakarta Project, the goal of which is an Open Source implementa-tion of servlets and JSP that will also serve as one of the reference platforms forthese technologies.

    As an essential element of feature-rich web sites and web-based applications,dynamic content generation continues to be the focus of much attention in the webdevelopment community. JSP is now positioned to play a major role in the ongoingevolution of web technology, and we look forward to seeing the next generation ofonline tools, services, and diversions that will be enabled by JavaServer Pages.

    JSP and Java 2 Enterprise Edition

    JSP is now an integral part of developing web-based applications using Java.Because of its ability to separate presentation from implementation logic by

  • 11 CHAPTER 1Introduction

    combining standard markup text with scripting elements and object-oriented com-

    1.3.1

    1.3.2

    jsp.book Page 11 Friday, March 17, 2000 2:32 PMponents, JSP provides an excellent front-end technology for applications that aredeployed over the web.

    Java platform editions

    In June 1999, Sun Microsystems announced that the Java 2 software platformwould be split into three editions, aimed at different categories of hardware deploy-ment platforms. The traditional Java Runtime Environment, or JRE, which con-tains all of the core classes in the formal language specification (including, forexample, the standard networking, utility, and graphical user interface classes), hasbeen renamed the Java 2 Standard Edition, or J2SE. The J2SE is targeted towardtraditional desktop computing platforms, such as Microsoft Windows and AppleMacintosh personal computers.

    A subset of the core classes, targeted toward handheld devices (for example,PDAspersonal digital assistantssuch as the 3Com PalmPilot), embedded pro-cessors (such as Internet-enabled toasters), and so-called information appliances(e.g., digital TV set-top boxes), comprises the Java 2 Micro Edition, or J2ME. Thegoal of J2ME is to provide a Java environment with minimal footprint, that never-theless supports the Java vision of Write Once, Run Anywhere program code.

    At the opposite extreme from J2ME is the Java 2 Enterprise Edition, or J2EE.Rather than subtract from the Java 2 core, as the micro edition does, J2EE bundlesthe core Java classes with extensions targeted toward enterprise application develop-ment. For example, J2EE includes support for Enterprise JavaBeans, which providesa set of standard abstractions for accessing corporate data stores, such as databasesand directory servers, with automatic support for transaction management andresource pooling.

    Given the inherent complexity involved in designing, constructing, and main-taining large-scale enterprise applications, however, Suns specification of J2EEincludes a set of guidelines for developing software using the J2EE platform. Theseguidelines take the form of a recommended base software architecture referred to asthe J2EE Application Model.

    Web-based applications

    A key element of the J2EE Application Model is the use of the web as a preferredmechanism for data delivery between the application and the end user, relying onthe web browser as a primary user interface for enterprise software. The advantageof this approach is that the web browser, in just the few short years since the birthof the World Wide Web, has been established as a ubiquitous, cross-platform,

  • JSP and Java 2 Enterprise Edition 12

    de facto standard for accessing data over the network. When an application relies on

    jsp.book Page 12 Friday, March 17, 2000 2:32 PMthe web browser for its user interface, there is no need for end users to install anyadditional software to run the application. And as new versions of the application aredeveloped and deployed on the server, end users automatically start using the newversion: end users need not take any local action to upgrade to the latest version.

    To facilitate web-based applications, then, both servlets and JSP are required ele-ments of the J2EE specification. And while both technologies can be used todynamically generate HTML to be sent to an end users web browser, only JSPenforces a strong separation between the presentation logic involved in displayingdata and the business or programming logic used to generate that data in the firstplace. This separation means that the design of the user interface, embodied in a setof JSP pages, can be carried out independently from the design of the other codethat runs on the server (e.g., interpreting requests, formulating database queries,and manipulating results). This independence leads to much more robust applica-tions, since changes to one part of the application generally do not require corre-sponding changes to other parts. Specifically, when using JSP, changes to thepresentation of the data (e.g., formatting of the data, design of the associatedgraphics, overall page layout) do not require any changes to the underlying servercode that supplied that data in the first place.

    Given Suns selection of servlets and JSPs as major components of J2EE, it isclear that support for these technologies will continue to grow. Even now, it is morethe rule than the exception that enterprise web application servers, such as NetscapeApplication Server, IBM WebSphere, and BEA WebLogic, include support for bothservlets and JSPs.

    In addition to growth in the market for software to deploy JSP, it is anticipatedthat improved development tools will soon be available. Currently, JSP developmentis essentially a manual process, but several of the web authoring tool vendors haveannounced support for JavaServer Pages in upcoming releases of their products,including Drumbeat 2000 from Macromedia, IBMs Visual Age for Java, andHomeSite from Allaire. JSPs built-in support for component-based design usingJavaBeans, discussed in a later section, promises to enable a new set of tools for cre-ating dynamic web pages graphically, using a visual programming approach to dragand drop server-side Java components into WYSIWYG editing tools. The ability tocreate sophisticated JSP pages without ever seeing HTML tags, let alone Java code,may soon be a reality.

  • 13 CHAPTER 1Introduction

    1.4

    1.4.1

    jsp.book Page 13 Friday, March 17, 2000 2:32 PMJSP benefits

    JSP offers several benefits as a system for dynamic content generation. First of all, asa Java-based technology, it enjoys all of the advantages that the Java language pro-vides with respect to development and deployment. As an object-oriented languagewith strong typing, encapsulation, exception handling, and automatic memorymanagement, use of Java leads to increased programmer productivity and morerobust code. Because there is a standard, published API for JSP, and because com-piled Java bytecode is portable across all platforms that support a JVM, use of JSPdoes not lock you into using a specific hardware platform, operating system, orserver software. If a switch in any one of these components becomes necessary, allJSP pages and associated Java classes can be migrated over as is. Because JSP isvendor-neutral, developers and system architects can select best-of-breed solutionsat all stages of JSP deployment.

    In addition, because it enables full access to the underlying Java platform, JSPcan readily take advantage of all of the other standard Java APIs, including those forcross-platform database access, directory services, distributed computing, and cryp-tography. This ability to leverage a wide range of data sources, system resources,and network services means that JSP is a highly flexible solution for creating feature-rich web-based applications.

    JSP itself offers several advantages as a system for dynamic content generation.Among these are improved performance over CGI and a programming model thatemphasizes component-centric application design. This programming modelenables developers using JSP to maintain a strict separation between the presentationelements of a web application and its underlying implementation. This separation, inturn, facilitates a division of labor within the web development team by establishinga well-defined interface between application development and page design.

    Performance

    Conventional CGI codes exist as external programs from the HTTP server. Whenthe server receives a request to be handled via CGI, it spawns one new process foreach request to execute the CGI code. This makes it easy for the web server to han-dle multiple simultaneous requests requiring the same CGI program, but in mostoperating systems, process creation is rather expensive: memory and other systemresources must be allocated and data and program code loaded before the code isrun. Since CGI programs are designed to generate a single response for a singlerequest, they execute quickly. After a CGI program has finished running, however,additional operating system resources are consumed when its process is destroyed.

  • JSP benefits 14

    As we will see in chapter 2, JSP is typically implemented via servlets. When a web

    jsp.book Page 14 Friday, March 17, 2000 2:32 PMserver receives a request for a JSP page, it forwards it to a special process dedicatedto handling servlet execution. This process is referred to as the servlet container. Inthe context of JSP, it is referred to as the JSP container.

    JARGON In older literature on server-side Java technologies, these containers are alsoreferred as enginesthat is, the servlet engine and the JSP engine.

    The servlet container is normally a separate process from the HTTP server, dueprimarily to the fact that the servlet container is a Java process, running a JVM, whilemost HTTP servers are written in other languages. The key factor here is that, forservlet containers associated with conventional HTTP servers, there is only one addi-tional process for the servlet container, which handles all servlet-related requests,including JSP. This process is initiated when the HTTP server starts up, and contin-ues to run until the HTTP server is shut down. Rather than create a completely newprocess for each request requiring dynamic content generation, all such requests areforwarded by the HTTP server to a single servlet container process.

    TIP For those HTTP servers that are written in Java, there is no reason the servletcontainer cannot be run as part of the same process. In fact, for many of theHTTP servers which are written in Java, all of the functionality of the HTTPserver is implemented via servlets, including the handling of requests for bothJSP and HTML files, so there is no distinction whatsoever between the HTTPserver and the servlet container.

    It is still a requirement that the servlet container handle multiple requests for agiven servlet or JSP at the same time, but this is accomplished via Java threads,rather than full-fledged processes. Threads are similar to processes, in that manythreads can be running simultaneously within a JVM. Threads require considerablyless overhead to create and destroy than processes, however; for this reason they aresometimes referred to as lightweight processes. Because they use less resources, theyare much more efficient than processes. For example, spawned processes often copythe memory of the parent process, whereas threads share memory with the parentthread. As a result, servlets and JSPs are much more efficient than traditional CGIprograms for generating dynamic web content.

  • 15 CHAPTER 1Introduction

    jsp.book Page 15 Friday, March 17, 2000 2:32 PMNOTE As a matter of fact, all of the code running within a Java Virtual Machine ispart of one thread or another. When a JVM first starts up, it creates an initialset of threads for managing itself (e.g., running the garbage collector, listen-ing for user interface events), as well as a thread for running user code. Thiscode can in turn create and run its own threads, as is the case for a servletcontainer using threads to handle HTTP requests.

    For even greater performance, some servlet containers are capable of runningin process, as part of the HTTP server process itself, even for those HTTP serverswhich are not written in Java. This makes communication of requests and responsesbetween the servlet container and the HTTP server much more efficient, and isaccomplished by running the servlet container itself as a thread within the HTTPserver. IBMs WebSphere, for example, supports in-process operation as an option,and the servlet container built into Version 4 of Netscapes iPlanet server productsonly runs in process.

    Furthermore, because all servlet and JSP requests are handled by the same pro-cess (i.e., the JVM), it is very easy for them to share resources, and thereby improveperformance. For example, database access is much quicker when employing a poolof reusable database connections that always remain open. Since CGI programs starta separate process for each request, it is much more difficult for them to shareresources. In the case of database access, for example, each CGI request must typi-cally open its own connection to the database, and close that connection when therequest is done. This adds additional overhead, which the servlet container canavoid by creating a connection pool during startup, and then sharing these connec-tions among individual request threads.

    As you are probably aware, Java class files are compiled to platform-independentbytecode rather than native assembly code. The job of the JVM is to interpret thisbytecode and turn it into platform-native instructions at run-time. Because of thisextra layer of interpretation required to run Java code, it is necessarily the case thatJava code will run slower than an equivalent program written in another program-ming language (for example, C or C++) and compiled to native code. Given thisfact, it might seem like Java would be a poor choice for dynamic content generation,since the speed with which requests can be turned into responses has a direct impacton the amount of traffic that can be handled by a web server.

    Recall, however, that most dynamic content generation systems in wide usetoday rely on interpreted scripting languages. The most popular language for CGIprogramming is Perl, an interpreted scripting language. Active Server Pages and

  • JSP benefits 16

    PHP are based on interpreted scripting languages. Server-Side JavaScript, like Java,

    1.4.2

    jsp.book Page 16 Friday, March 17, 2000 2:32 PMis compiled into a platform-independent format, so it also requires a run-time inter-preter. ColdFusion tags are likewise interpreted at run-time on a per-request basis.

    Compared to the most popular alternatives, then, JavaServer Pages does not suf-fer a relative performance hit because of its reliance on an underlying interpreter.Furthermore, because of the popularity of Java as a programming language, manytechniques have been introduced in recent years for improving Java run-time per-formance, such as Just-In-Time (JIT) compilation and generational garbage collec-tion. In practice, then, Java performance is more than adequate for dynamiccontent generation, given adequate server hardware. At the same time, hardwareand operating systems vendors continue to actively research new methods forimproving JVM performance, as they compete for top honors in various Java bench-marks. And as Java performance continues to improve, the performance of Java-Server Pages also improves. So, while Sun Microsystems and all of the othervendors of servlet and JSP products continue to work on the performance of thebasic JavaServer Pages API, JSP also benefits indirectly from all of the resourcesbeing devoted to Java performance in general.

    Reusable components

    Although JavaServer Pages enables programmers to implement dynamic content gen-eration by including Java source code directly in web pages, it also includes a set ofHTML-like tags for interacting with Java objects residing on the server. In particular,these tags are designed for creating, querying, and modifying server-side JavaBeans.

    JavaBeans are objects, written in Java, whose implementations conform to a setof conventions designed to promote modularity and reusability. JavaBeans uses aprogramming style that leads to self-contained chunks of program code that encap-sulate related data, functionality, or behavior, which may be used and reused in mul-tiple contexts without having to know the details of their inner operation. As aresult, JavaBeans can readily be connected together and combined in order to pro-vide more sophisticated or application-specific capabilities. The generic computerterm for an object that exhibits this sort of plug-and-play interoperability is a compo-nent. JavaBeans, then, is one example of a component programming model. Othersinclude Microsofts ActiveX (which plays a similar role in Active Server Pages to therole of JavaBeans in JavaServer Pages) and CORBA, a component interoperabilitystandard developed by the Object Management Group (OMG), an industry consor-tium for distributed, cross-platform, object-oriented middleware.

    A component, then, is a stand-alone object representing a collection of proper-ties and behavior. Because these properties and behavior can be accessed without

  • 17 CHAPTER 1Introduction

    regard for the underlying implementation, it is possible to describe a components

    1.4.3

    jsp.book Page 17 Friday, March 17, 2000 2:32 PMcapabilities independent of the programming language in which it was originallywritten. A component could be used in a second programming language (for exam-ple, a scripting language), or even be applied using visual tools, with no programcode at all. In the case of JavaServer Pages, components written as JavaBeans areaccessed not by means of a programming language, but via an alternate syntax. Spe-cifically, JSP provides HTML-like tags for accessing JavaBeans on a page, and for dis-playing and modifying their properties. For complete details, see chapter 5.

    The primary virtue of component-centric design is reusability. Because compo-nents are required to be self-contained, programmers do not have to understandany complicated relationships between objects in order to be able to use them. Acomponent may call on other objects behind the scenes, but the abstract interfacethrough which the component is accessed and manipulated, if designed properly,will mask the underlying complexity. Because components tend to be targetedtowards specific tasksrepresenting a particular set of data, performing a specificbehaviorit is easy to determine what functionality the component provides, andtherefore under what circumstances it should be used. To some extent, componentsare reused by virtue of the fact that they are easy to use in the first place.

    The benefit of this reusability is productivity. If a component is already availableto perform some task, that is one less piece of code that needs to be written,debugged, and maintained. Furthermore, components are generally not context-sensitive. For example, the same JavaBean can be deployed in a servlet, an applet, ora JSP page, creating additional opportunities for reuse.

    Separating presentation and implementation

    By taking advantage of JSPs built-in support for JavaBeans, it becomes possible tomaintain a strict separation between data presentationthe display of informationto the end userand program implementationthe code used to generate thatinformation in the first place. The benefit of decoupling these two aspects is thatchanges to one can be made without requiring any changes to the other. The waydata is displayed (e.g., font selection, color scheme, page layout) can be revisedwithout ever having to modify any Java code. Similarly, as long as the componentinterfaces remain unchanged, the underlying implementation can be rewritten (e.g.,to improve performance or maintainability) with no effect on any JSP pages thatuse those components.

    Given this goal, then, JSPs provide a very simple and elegant means of maintain-ing the separation of these two elements of a web-based application: syntax. Byleveraging JSPs HTML-like tags for accessing JavaBeans and their properties, JSP

  • JSP benefits 18

    pages can be written that contain no Java source code. If none of the available tags

    jsp.book Page 18 Friday, March 17, 2000 2:32 PMprovides the functionality needed, you can, if so inclined, write your own applica-tion-specific tag library using the JSP tag extension mechanism. If the JSP pagecontains only tags and no Java code, the first requirement for enforcing separationof presentation and implementation has been met, since there is no implementationcode mixed in with the presentation code.

    The second requirement is equally easy to describe: there should be no HTMLcode in your JavaBeans. At first blush, this might sound like an absurd notion.(JavaBeans are written in Java, not HTML!) However, theres nothing stopping aprogrammer from creating a JavaBean whose properties include strings of HTMLcode. A JSP page could then access these properties, inserting that HTML code intothe page through the corresponding property tags. It may be tempting to give yourJavaBean the ability to, say, generate a large HTML table from the results of adatabase query, but any time it is necessary to change the appearance of the table,that Bean must be edited, compiled, and tested before that change can be put intoeffect. For this reason, in order to achieve separation of presentation and implemen-tation, its also necessary to keep presentation code out of the implementation code.

    There will be times, though, when generating HTML code programmatically isthe best solution. Consider an on-line banking application implemented via Java-Server Pages. There would likely be JavaBeans representing a customers accounts,as well as each of the transactions involving those accounts. For maximum reusabil-ity, good component-centric design would dictate that these application-orientedJavaBeans would model only the banking aspects of accounts and transactions, andwould not include properties that return, say, account balances in HTML format.These Beans could then be readily deployed in other application contexts (e.g., aJava applet), which have no use for such web-oriented baggage. It would likelyprove fairly cumbersome, however, to write a JSP page that uses these Beans to dis-play, say, the last 10 transactions for an account. This is primarily because JSP doesnot include any built-in tags for iterating through Bean properties. To solve thisdilemma, it appears that you have no choice but to either include Java scriptingcode in the JSP, or provide for HTML output by the Bean.

    Fortunately, JavaServer Pages provides a third alternative, specifically gearedtoward programmatic generation of HTML using Java code. As suggested infigure 1.3, this is the role of JSPs tag extension mechanism, which allows Javaprogrammers to implement new JSP tags and package them in application-specificlibraries that may then be imported into individual JSP pages. For this hypo-thetical banking application, then, the best way to maintain separation between

  • 19 CHAPTER 1Introduction

    presentation and implementation is to develop a set of custom tags for represent-

    1.4.4

    jsp.book Page 19 Friday, March 17, 2000 2:32 PMing complex account information, such as transaction lists, via HTML. Custom tags still have the problem that, in

    order to change the display of data controlledvia custom tags, programming is required. Thisis unavoidable, however, if programmatic gen-eration of HTML is required. The advantage ofimplementing HTML generation via customtags is two-fold. First, custom tags provide ameans for avoiding Java code in the JSP filesthemselves. JSP files can continue to rely on asingle, consistent, HTML-like syntax. Second,on the programming side, the HTML genera-tion is isolated within the tag library code. Thetag library will likely have dependencies uponyour JavaBeans code, but not vice versa. Cus-tom tags provide a well-defined inter facebetween the presentation and implementation, without contaminating the JSP fileswith implementation code, or the Bean properties with presentation code.

    Achieving division of labor

    An important side effect of this decoupling of presentation and implementationthrough JSP is that it promotes a clear division of labor in the development andmaintenance of web applications for dynamic content generation. It is the rare indi-vidual indeed who possesses outstanding skills in both programming and artisticdesign. Although many companies try, rarely are they fortunate enough to find afirst class web designer who also possesses strong Java development skills or the cor-ollary, a true Java guru with strong graphics and layout skills.

    As a result, most web application development teams are cross-functional innature, representing multiple specialties. Designers, graphic artists, and HTML cod-ers are responsible for the presentation. Java programmers and system architects areresponsible for the implementation. Large corporate teams may also include editors,marketing consultants, database administrators, network engineers, and systemadministrators. All of the team members have important contributions to make tothe focus, design, and content of the web application, but when it comes time foractual implementation, efficiency will be a direct result of the extent to which theparticipants are able to work independently. When a clear division of labor can beput in place, such that the need to coordinate work between team members is

    Figure 1.3 Support of JSP features for the separation of presentation and implementation.

  • JSP benefits 20

    minimized, work on multiple parts of the implementation can be carried out simul-

    jsp.book Page 20 Friday, March 17, 2000 2:32 PMtaneously. Studies have repeatedly shown that communication is the major bottle-neck in team productivity; if communication needs can be reduced during thecritical implementation phase, the productivity rewards can be great.

    Similarly, when changes to the application are required after initial development,the fewer team members that need to be involved in order to effect that change, themore quickly the modification can be put in place. For example, an important con-cern for an on-line service provider is the usability of their web site: Is content easyto find? Are services easy to use? Usability, then, is critical to customer satisfactionand retention. In the interest of usability, the presentation aspects of a web applica-tion may undergo almost constant review and revision. The implementation of thebusiness and programming logic behind the application, however, tends to evolvemuch more slowly.

    If the team members responsible for these two elements of the application canwork independently, then, both the initial development and later refinements canbe carried out more efficiently. As described above, JSPs support for component-centric design promotes the establishment of clear interfaces for accessing the func-tionality of server-side objects implemented as JavaBeans. The HTML-like tags pro-vided by JavaServer Pages for accessing JavaBeans can then take advantage of theseinterfaces to achieve (and enforce) separation of presentation and implementation.

    In practical terms, this means that page designers can focus on HTML and appli-cation engineers can focus on Java. The team as a whole develops the requirementsthat drive the web applications design. The programmers then translate theserequirements into a set of properties and behaviors to be implemented as Java-Beans. These properties and behaviors then provide the foundation for dynamiccontent generation to be leveraged by the presentation team via JavaServer Pages.And, once this foundation is established, both teams can work independently torefine their contributions to the applicatione.g., enhancing the look and feel ofthe application, or increasing its run-time efficiencywithout negatively impactingthe performance of the other team.

  • T

    jsp.book Page 21 Friday, March 17, 2000 2:32 PMhis chapter coversWriting your first JSP

    Scripting and XML tag conventions

    How JSPs work

    Handling errors 2Fundamentals21

  • Writing your first JSP 22

    Now that youve seen an overview of JSP, where it has come from, and what it

    2.1

    2.1.1

    2.1.2

    jsp.book Page 22 Friday, March 17, 2000 2:32 PMoffers, its time to dive into the technology itself. Subscribing to the theory that itsbetter to jump in headfirst than to wade in one step at a time, well immediatelylook at a few examples, followed by a discussion of the basic syntax of JSP tags.Next, well consider the requirements for setting up a web server for use with Java-Server Pages. Finally, well examine how the technology actually works, and discusshow the implementation of JSP affects its operation.

    Writing your first JSP

    Our first objective in this chapter is to set the stage with examples that illustrate theflexibility and power of JSP as a solution for dynamic content generation. We wontfocus too much on the detailsthere will be plenty of that later. The intent here issimply to give you an idea of the ground to be covered in the coming chapters.

    About the examples

    As indicated in chapter 1, a strength of JSP is its ability to provide dynamic contentgeneration via a familiar, HTML-like syntax. At the same time, however, this familiarsyntax can make it difficult for those new to JSP to immediately recognize where itselements are being used within a page. Therefore, in the examples in this book thatcombine JSP elements with other static content (typically HTML), we have adoptedthe convention of marking JSP tags in such pages and page fragments in boldface.The intent of this convention is to enable readers to easily distinguish JSP contentfrom the surrounding static document content.

    Hello, World!

    No software book would be complete without an example that prints out Hello,World! so here is a JSP that does just that:

    Hello, World!

    At this point, youre probably thinking, Hey! Thats nothing but HTML! Andyoure exactly right. It is nevertheless, a valid JSP file. This file could be added to thedocument hierarchy of a web server configured to run JSP and, if it were assignedthe proper extension (typically .jsp), then any request for this document would beinterpreted as a JSP request. The web server would forward the request to the local

  • 23 CHAPTER 2Fundamentals

    JSP container for processing. Naturally, the JSP container wouldnt find any actual

    2.1.3

    jsp.book Page 23 Friday, March 17, 2000 2:32 PMJSP elements, and so would simply output the HTML as written. This is a fairlyroundabout way of delivering a static HTML document, but it would certainly work.

    Hello, World! revisited

    Having established the fairly uninteresting fact that all valid HTML documents arealso valid JSP documents, lets consider a more motivating example. Heres a filethat generates content dynamically through the use of a pair of JSP tags that sup-port scripting:

    Hello, !

    Without getting into the details, this JSP first declares a Java String variable namedvisitor, and then attempts to initialize it from the current HTTP request. If novalue for this variable is present in the request, a default value is assigned. A JSPexpression is then used to insert the value of this variable into the HTML output ofthe page.

    Request parameters are passed into JSP pages using the normal HTTP parametermechanisms. For HTTP GET requests, encoded parameter values are simplyappended to the URL. For HTTP POST requests, a more complicated protocol isused to send parameter data behind the scenes. In practice, URLs longer than 255characters can be problematic, so POST requests are the standard when a largeamount of parameter data is required.

    WARNING This length restriction on URLs is driven by backward-compatibility with old-er software. The HTTP/1.1 specification actually imposes no a priori limitson URL length, but there are older servers, proxies, and browsers that cannothandle URLs which exceed this 255-character limit.

    For the purposes of this example, lets assume the URL for this JSP page is http://server/webdev/fundamentals/helloScript.jsp. If a web browser were used to requestthis URL via an HTTP GET request, the JSP container would process this page andrespond with the following:

    Hello, World!

  • Writing your first JSP 24

    If the appropriate parameter value were added to this URL, however, a different

    jsp.book Page 24 Friday, March 17, 2000 2:32 PMresult would be obtained. If the requested URL was http://server/webdev/funda-mentals/helloScript.jsp?name=Flynn, for example, the response from the JSP con-tainer would instead be:

    Hello, Flynn!

    In the first case, without the parameter value, the script used the default value forthe pages visitor variable. In the second case, the script retrieved the value of thename parameter from the request, and so was able to generate more personalizeddynamic content.

    If you were to use a web browser to try out these examples, you might betempted at this point to use the browsers View Source command to look at theHTML in this response. If you were to do so, you might expect to see the contentsof the original JSP file. Instead you would see something like the following:

    Hello, Flynn!

    If you are new to dynamic content generation, you may be wondering what hap-pened to all of the JSP tags (e.g., ). This result looks like someoneslipped in the file from the previous section, inserting the name Flynn in place ofsome of the original text.

    In fact, thats very close to whats actually happening. Keep in mind that theweb browser sees only the response from the web server to its request, which mayor may not correspond to some original source document. The browser has no wayof knowing that, when the web server receives a request corresponding to a JSPpage, that request is forwarded to the JSP container for processing. It is the JSP con-tainer that reads and interprets the code in the corresponding file to generate