Tải bản đầy đủ (.pdf) (584 trang)

Manning web development with javaserver pages

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (15.67 MB, 584 trang )

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

Web Development with JavaServer Pages


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


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

Web Development with

JavaServer Pages
DUANE K. FIELDS
MARK A. KOLB

MANNING
Greenwich
(74° w. long.)


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

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 Department
Manning Publications Co.
32 Lafayette Place
Greenwich, CT 06830


Fax: (203) 661-9018
email:

©2000 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have the
books we publish printed on acid-free paper, and we exert our best efforts to that end.

Library of Congress Cataloging-in-Publication Data

Manning Publications Co.
32 Lafayette Place
Greenwich, CT 06830

Copyeditor: Elizabeth Martin
Typesetter: Tony Roberts
Cover designer: Leslie Haimes

Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – CM – 03 02 01 00


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


To Kris—
for 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 PM

brief contents
1



Introduction 1

2



Fundamentals 21

3




Programming JSP scripts

4



Actions and implicit objects 84

5



Using JSP components 111

6



Developing JSP components 147

7



Working with databases 178

8




Architecting JSP applications 209

9



An example JSP project

10



Deploying JSP applications 297

11



Performing common JSP tasks 321

12



JSP by example 366

13




Creating custom tags 403

14



Implementing advanced custom tags 436

49

250


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

viii

BR I E F C O NT E N T S

A



Running the reference implementation 477

B




Incorporating Java applets 489

C



JSP resources 503

D



JSP syntax reference 508

E



JSP API reference 524
index 545


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

contents
preface

xix

acknowledgments


xxi

about this book xxiii
about the authors xxvii
author online

xxviii

about the cover illustration

1

Introduction

xxix

1

1.1

What is JSP? 2

1.2

Evolution of dynamic content technologies 2
Common Gateway Interface 3 ColdFusion 5
Active Server Pages 6 Server-Side JavaScript 6
PHP 7 Java servlets 7 JavaServer Pages 9







1.3



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


1.4

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



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

x

CO N TE NT S

2


Fundamentals 21
2.1

Writing your first JSP 22
About the examples 22 Hello, World! 22
Hello, World! revisited 23 Hello, World! the Bean
edition 25 Hello Real World 27






2.2
2.3

Tag conventions 28
Scripting-oriented tags 29



XML-based tags 29

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







3

Programming JSP scripts

49

3.1

Scripting languages

50

3.2

JSP tags

3.3

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

52


3.4


Scripting elements 67
Declarations 67 Expressions 71


3.5



Scriptlets 74

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




Exception



3.6

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



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


CONTENTS

4

Actions and implicit objects
4.1

84

Implicit objects 85
Servlet-related objects 87 Input/Output 88
Contextual objects 95 Error handling 103




4.2

Actions 104
Forward 104 Include 108
Bean tags 110


5

Using JSP components
5.1




Plug-in 110

111

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






5.2

JavaBean fundamentals 117
The different types of JavaBeans 120

5.2

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





6

Developing JSP components 147
6.1

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








6.2

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

xi


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

xii


CO N TE NT S

6.3

Bean interfaces 169
The BeanInfo interface 169 The Serializable
interface 170 The HttpSessionBindingListener
interface 171 Other features of the Bean API 172






6.4

7

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

Working with databases
7.1
7.2

178

JSP and JDBC 179

JNDI and data sources 180



Prepared statements 181

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




7.3

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


8

Architecting JSP applications

209

8.1


Web applications 210
Web application flow 212
Architectural approaches 213

8.2

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



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

CONTENTS

8.3

Servlet-centric design 219
Hello, World—with servlets 220 JSP and the servlet
API 221 Servlets for application control 224 Servlets
for handling application logic 225 Servlets as single
entry points 226 Handling errors in the servlet 230
Example: servlet-centric employee browser 230
EmployeeBean 232 FetchEmployeeServlet 235
JSP employee list 238 JSP page viewer 239















8.4

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




8.5

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







9

An example JSP project
9.1

250

Introduction 251
Project motivations 251 Application requirements 251
Application modules 253 Building a FAQ
component 254




9.2

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


9.3

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

Updating an FAQ 285




xiii


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

xiv

CO N TE NT S

9.4

The web access module 290
The FaqServlet 290 Viewing a single FAQ 292
Viewing all the FAQs 293 A table of contents view 294
Plain text view 296




10

Deploying JSP applications 297
10.1

This means WAR 298

WAR is XML 299 Waging WAR 301


11

10.2

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

10.3

Maintaining a WAR footing

319

Performing common JSP tasks 321
11.1

Handling cookies 322
Managing cookies 322 The Cookie class 323
Example 1: setting a cookie 324
Example 2: retrieving a cookie 326


11.2

Creating error pages 329
An erroneous page 330 Data collection methods 330

Sending electronic mail 335 The error page 337




11.3

Mixing JSP and JavaScript

340

11.4

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















11.5



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


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

CONTENTS

11.6

12

Miscellaneous tasks 361
Determining the last modification date 362
Executing system commands 363
Generating XML 364

JSP by example
12.1

366

A rotating banner ad 367

The BannerBean 367 Using the Bean 368


12.2

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


12.3

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


12.4

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




12.5

12.6


An index generator 391
A basic implementation 391
Going further 398

An improved version 394

A button to view JSP source 398
Displaying 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 403
13.1

Role of custom tags

404

13.2

How tag libraries work


405

xv


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

xvi

CO N TE NT S

13.3

Tag library descriptors

408

Library elements 409 Tag elements 410
Attribute elements 411


13.4

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


419


13.5

Example tag library

13.6

Content substitution

13.7

Tag attributes 422

13.8

Content translation 427
URL rewriting 427 HTML encoding 431

420



13.9

14

B

435


Implementing advanced custom tags 436
14.1
14.2

A

To be continued

Interacting tags 437
Interaction mechanisms 437
Flow of control 449
Conditionalization 450

14.3

Packaging the tag library

14.4

For further information



Outlining tags 439



Iteration 458

475

476

Running the reference implementation
478

A.1

Prerequisites

A.2

Installation

A.3

Constructing an application

478
485

Incorporating Java applets 489
489

B.1

Browser support for Java 2

B.2

The plug-in action


B.3

Example: applet configuration

491
496

477


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

CONTENTS

C

D

JSP resources

503

C.1

Java implementations

503

C.2


JSP-related web sites

504

C.3

JSP FAQs and tutorials

C.4

JSP containers

C.5

Java application servers with JSP support

C.6

JSP development tools

C.7

Tools for performance testing

C.8

Mailing lists and newsgroups

504


505
506

JSP syntax reference 508
D.1

Content comments

508

D.2

JSP comments

D.3

<jsp:declaration>

D.4

<jsp:directive.include>

D.5

<jsp:directive.page>

D.6

<jsp:directive.taglib>


D.7

<jsp:expression>

D.8

<jsp:forward>

D.9

<jsp:getProperty>

509
510
511

512
513

514

515

D.10

<jsp:include>

D.11


<jsp:plugin>

D.12

<jsp:scriptlet>

D.13

<jsp:setProperty>

D.14

<jsp:useBean>

516

517
518
520
521

522

506
507

505

xvii



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

E

JSP API reference 524
E.1

JSP Implicit Objects

525

E.2

Package javax.servlet

525

E.3

Package javax.servlet.http

E.4

Package javax.servlet.jsp

E.5

Package javax.servlet.jsp.tagext


index

545

530
535
539


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

preface
In late 1998 we were asked to develop the architecture for a new website. Our
employer, a vendor of enterprise software for system and network management,
had an unconventional set of requirements: that the site be able to provide product
support data customized for each customer; and that the support data be tailored
to the software the customer had already purchased, as well as the configurations
already selected.
Of course, the website needed to look sharp and be easy to navigate. Management software, which of necessity must be flexible and support a wide range of
operating conditions, tends to be very complex. This particular software was targeted at Internet and electronic commerce applications, so using the web as a major
component of product support was a natural fit. By personalizing web-based support for each customer, this inherent complexity would be reduced, and the customer experience improved. But how to accomplish that ... and how to do it within
the 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 work
unhindered in the limited time available. The ability of these two groups to
progress independently, without costly rework, was crucial. A solution that could
provide dynamic content as an add-on to otherwise conventional HTML files clearly
was the best approach. We briefly considered, then just as quickly dismissed, the
notion of building our own dynamic context system. There just wasn’t enough time
to deliver both a publishing system and a website.



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

xx

PREFACE

At the time we were already familiar with Java servlets. Indeed, servlets were a
key element of the architecture of the product to which this site would be devoted.
We mulled over using servlets for the site itself but were concerned with how this
would affect those responsible for the content, graphics, and layout of the site.
As we researched the problem further we were reminded of an ongoing initiative
at Sun Microsystems called JavaServer Pages (JSP). JSP was still being refined, and
Version 1.0 was months away. However, it was intended to become a standard Java
technology, and it used Java servlets as its foundation. It also allowed us to implement dynamic content on top of standard HTML files. Best of all, it worked! As we
became 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 went
through major changes along the way. Hair was pulled, teeth were gnashed, lessons were learned. Fortunately, we obtained a great deal of help from the JSP community—the developers at Sun and the other JSP vendors, as well as our fellow
early adopters.
This book thus serves a twofold purpose. First, we hope to help future users of
JSP by sharing the hard-earned lessons of our experience. We offer them what we
hope is a helpful guide to the current JSP feature set: JavaServer Pages is now at version 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 community 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 PM

acknowledgments

We recognize the support and understanding of the many people who helped make
this book possible. We acknowledge:
T. Preston Gregg, our development manager, for allowing us to make the early
leap to a JSP architecture, before the technology was considered ready for prime
time. This head start was painful at times, but ultimately proved a boon to our web
development 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 writing of the this book include Kirk Drummond and Ward Harold.
The JSP design team at Sun Microsystems, especially Eduardo Pelegrí-Llopart. His
assistance 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 their
insights and expertise to the development community through their unselfish participation in mailing lists, newsgroups, and the web. Double thanks to everyone
participating in the Jakarta and Apache projects for their outstanding work in the
Open Source arena. You are all instrumental to the continuing success of Java and
establishing it as a lingua franca for Internet development.
Our publisher, Marjan Bace, for giving us this opportunity, and our editor, Elizabeth Martin, for her yeoman’s effort in polishing this manuscript. Their insights
and guidance were invaluable to the completion of this book.
Our reviewers, whose comments, criticisms, and commendations throughout the
development of this book advised, corrected, and encouraged us. Our deep appreciation is extended to Michael Andreano, Ruslan Belkin, Drew Cox, Jose Luis Diaz,
Sergio Queijo Diaz, Richard Friedman, Dennis Hoer, Paul Holser, Vimal Kansal,


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

xxii

ACKNOWLEDGMENTS

Sachin Khanna, Daniel Kirkdorffer, JJ Kuslich, Eric Lunt, Dave Miller, Vincent
Partington, Harold Sasaki, Edward Toupin, Wong Kok Wai, and Paul Williamson.
We are also indebted to Ted Kennedy, our review editor, for coordinating this

imposing task.
Our friends, families, and coworkers for their unfailing support, assistance, and
tolerance throughout the writing process. Without them this book could not have
been possible.


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

about this book
JavaServer Pages is a technology that serves two different communities of developers. Page designers use JSP technology to add powerful dynamic content capabilities
to web sites and online applications. Java programmers write the code that implements those capabilities behind the scenes.
Web Development with JavaServer Pages is intended to present this technology to
both groups. It is impossible in a book of this length to provide all the background
information required by this subject, and, for this reason, we do not attempt to
describe the HTML markup language. It is assumed that the reader is sufficiently
familiar with HTML to follow the examples presented. It is likewise assumed that
the reader is familiar with URLs, document hierarchies, and other concepts related
to the design, operation, and management of web servers.
We also do not include a primer on the Java programming language. As with
HTML, there is a wealth of reference information available on the language itself.
Our focus here is strictly on JavaServer Pages. Obviously, JSP interacts strongly with
Java 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, but
the 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 dynamic
content to web pages, and the benefits it provides compared to other dynamic content systems.



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

xxiv

ABOUT THIS BOOK

Chapter 2 presents introductory examples, as well as an overview of the basic
conventions for JSP tags. This is followed by a discussion of how JSP interacts with
the web server and the end user’s browser, and how JSP pages actually work to produce dynamic content. As it covers all of the major aspects of JSP technology at a
high 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 JSP
tags is presented, with the exception of those specific to JavaBeans. The first three
categories are covered in chapter 3.
Chapter 4 introduces action tags, and describes the implicit Java objects accessible from all JSP pages. In both of these chapters, particular emphasis is placed on the
application of these tags and objects to dynamic content generation via scripting.
The scripting examples use the Java programming language, and may be of secondary interest to page designers. Because this chapter introduces most of the major
functionality provided by JavaServer Pages, it is intended for a general audience.
Chapters 5 and 6 cover JSP’s component-centric approach to dynamic page
design through the use of JavaBeans and JSP Bean tags. The JSP tags covered in
chapter 5 allow page designers to interact with Java components through HTMLlike tags, rather than through Java code. This chapter will introduce the JavaBeans
component model, and demonstrate JSP’s interaction with JavaBeans through the
use of the JSP Bean tags.
Chapter 6 builds on this foundation, teaching Java programmers how to develop
their own JavaBeans for use with JSP.
Chapter 7, geared primarily toward Java developers, covers techniques for working with databases through JSP. Nowadays, most large-scale web sites employ databases for at least some portion of their content. Ad management, user registration
information, inventory records, and community services are all quite commonly
handled through a database. JSP and relational databases make a good combination.
The relational database gives us the organizational capabilities and the performance
necessary to manage dynamic data. By combining the power of a relational database

with the flexibility of JSP for content presentation and front-end design, it is practical to build rich, interactive interfaces to your data.
In chapter 8, we discuss several architectural models useful for developing JSP
applications. We examine the various architectural options available when we combine JSP pages with servlets, Enterprise JavaBeans, HTML, and other software elements 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


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

ABOUT THIS BOOK

xxv

audience. The bulk of this chapter, which focuses on how these architectural models
are implemented, is geared toward Java programmers.
In chapter 9, we apply the JSP programming techniques we covered in previous
chapters to the development of a real world, enterprise web application. In a
chapter-length example, we will be developing a system for managing and presenting lists of frequently asked questions (FAQs). This chapter is based on a project
the authors recently completed for a major software company’s customer support
site. 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 application isn’t useful until it is successfully deployed. The JSP and servlet specifications
have introduced several new facilities for easing and improving the deployment of
Java-based web applications. Chapter 10 explains Sun’s new Web Archive format
and how it can be used to create packaged JSP applications. Since both code and
pages are stored together in a packaged application, this chapter should be of interest 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 examples
of form management, interface design, and error handling in chapter 11 have been
designed to be representative of common tasks for which you might employ JSP.
Chapter 12 focuses on full-fledged applications that illustrate the various techniques

and practices presented in the other chapters of this book.
Chapter 13 covers the development, deployment, and use of custom tag libraries. This material focuses primarily on the implementation of custom tags by Java
programmers. From the perspective of jointly designing a set of application-specific
tags, page designers may find some benefit in reviewing the introductory sections of
this chapter, which discuss the types of functionality that can be provided by custom
JSP tags. In chapter 14, we expand upon the topic of custom tags with additional
examples that take advantage of more advanced features of Java and JSP.
There are five appendices in this book. Appendix A provides instructions for
installing and running Tomcat, the free reference implementation for both servlets
and JavaServer Pages jointly developed by Sun Microsystems and the Apache Software Foundation. Tomcat provides an Open Source, zero-cost platform for JSP
development that is fully compliant with the published specifications. This chapter
assumes no programming knowledge, but does require familiarity with the operating system on which the software is to be installed.


×