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

Manning JSTL in action jul 2002 ISBN 1930110529 pdf

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 (5.92 MB, 481 trang )


JSTL in Action



JSTL in Action
SHAWN BAYERN

MANNING
Greenwich
(74° w. long.)


For electronic 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.
209 Bruce Park Avenue
Greenwich, CT 06830

Fax: (203) 661-9018
email:

©2003 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 they publish printed on acid-free paper, and we exert our best efforts to that end.

Bayern, Shawn
JSTL in Action /Shawn Bayern.
p.
cm.
Includes bibliographical references and index.
1. Java (Computer program language). 2. Title.

Manning Publications Co.
32 Lafayette Place
Greenwich, CT 06830

Copyeditor: Tiffany Taylor
Typesetter: Denis Dalinnik
Cover designer: Leslie Haimes

ISBN 1-930110-52-9 (alk. paper)
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – VHG – 05 04 03 02


For my future wife and kids,
who, when I meet and conceive them,
respectively,

will likely be my love and my inspiration



brief contents
PART 1

PART 2

BACKGROUND .................................................... 1
1

Q

Dynamic web sites 3

2

Q

Foundation: XML and JSP 15

LEARNING JSTL ............................................... 41
3

Q

The expression language 43

4


Q

Controlling flow with conditions 77

5

Q

Controlling flow with loops 95

6

Q

Importing text 115

7

Q

Selecting XML fragments 139

8

Q

Working with XML fragments 153

9


Q

Database-driven pages 181

10

Q

Formatting and internationalization 215

vii


viii

BRIEF CONTENTS

PART 3

PART 4

JSTL IN ACTION .............................................249
11

Q

Common tasks 251

12


Q

Dynamic features for web sites 279

13

Q

Case study in building a web site 301

JSTL FOR PROGRAMMERS ............................327
14

Q

Control and performance 329

15

Q

Using JSTL to develop custom tags 361

APPENDICES ......................................................................389
A

Q

JSTL reference 389


B

Q

JSTL API (for developers) 409

C

Q

Database tags and SQL 421

D

Q

References and resources 433


contents
preface xix
acknowledgments xxi
about this book xxiii
about the cover illustration xxvii

PART 1

1


BACKGROUND .................................................... 1
Dynamic web sites 3
1.1

The boring life of a web browser 4

1.2

The simple ideas behind dynamic web content 6

1.3

What you need to run JSTL 9
JSP containers

10

1.4

Real-world web applications 11

1.5

Summary 14

ix


x


CONTENTS

2

Foundation: XML and JSP
2.1

Introduction to XML 16
A dose of tag terminology

2.2

15

17

Q

The relevant rules of XML

21

Introduction to JSP 23
JSP tag syntax 24 Standard JSP tags 25
JSP tag libraries 29 Other JSP directives 32
JSP comments 33 How JSP organizes data 34
Q

Q


Q

2.3

PART 2

3

Summary 39

LEARNING JSTL ...............................................41
The expression language
3.1

43

Expressions and the <c:out> tag 44
What expressions look like 45
Default values in <c:out> 46

3.2

Q
Q

Where expressions work 46
Special characters and <c:out> 47

Scoped variables and the expression language 48
Basic syntax to access scoped variables 48

Different types of scoped data 50

3.3

Request parameters and the expression language
HTML forms

3.4

55

Q

A page that reads request parameters

55
62

More powerful expressions 63
Different ways to access properties 64 Accessing other data with the
expression language 65 Comparisons 67 Boolean operations
and parentheses 69 Multiple expressions 70
Q

Q

Q

3.5


Saving data with <c:set> 71

3.6

Deleting data with <c:remove > 74

3.7

Summary 75

Q


CONTENTS

4

Controlling flow with conditions 77
4.1

Different kinds of decisions 79

4.2

Yes-or-no conditions with <c:if> 79
The basic syntax of <c:if> 80 Using <c:if> within HTML
tags 82 Multiple <c:if> tags 82 Nested <c:if> tags 84
The var and scope attributes 86
Q


Q

4.3

Q

Mutually exclusive conditions with <c:choose>, <c:when>,
and <c:otherwise> 88
Why JSTL has complex conditional tags 88 How the complex conditional tags work 89 Rules for using the complex conditional tags 93
Q

Q

4.4

5

Summary 94

Controlling flow with loops 95
5.1

General-purpose looping with <c:forEach> 96

5.2

Iterating over strings with <c:forTokens> 98
How JSTL parses strings 100

5.3


Advanced iteration with <c:forEach> and
<c:forTokens> 101
Looping over part of a collection 101
Loop status 106

5.4

Q

Looping over numbers 104

Loop example: scrolling through results 107
Understanding the example 109
Using varStatus in the example 111

5.5

6

Summary 113

Importing text 115
6.1

Including text with the <c:import> tag 117
Absolute and relative URLs 117 Retrieving data from URLs 121
Saving information for later 122 Communicating with
imported pages 124 Import example: a customized header 127
Q


Q

Q

6.2

Redirecting with <c:redirect> 132

6.3

Formatting URLs with <c:url> 134
How to use <c:url> 134

6.4

Summary 137

Q

Why to use <c:url> 135

xi


xii

CONTENTS

7


Selecting XML fragments 139
7.1

XPath’s vision of an XML document 140

7.2

XPath’s basic syntax 142
Deep descendants 143 Attributes 144 Predicates and
element order 145 Strings and booleans 146
Q

Q

Q

7.3

XPath variables and JSTL 147

7.4

JSTL, XPath, and namespaces 148

7.5

More advanced XPath 149
Nodes and axes 149


7.6

8

Q

Contexts 150

Q

Further reading

151

Summary 152

Working with XML fragments 153
8.1

Parsing documents with <x:parse> 154
Sources of XML 155

8.2

Accessing XML with <x:out> and <x:set> 156
Finding a document 156
The <x:set> tag 158

8.3


Q

The <x:out> tag

157

Control flow based on XML documents 159
Simple conditions with <x:if> 160 Compound conditions
with <x:choose> 162 Looping over parts of a document
with <x:forEach> 164
Q

Q

8.4

XML transformations using JSTL 169
Simple transformations with <x:transform> 170 Using the
var attribute 172 XSLT parameters 174 Advantages of using
XSLT within JSTL 174
Q

Q

Q

8.5

An XML example: reading RSS files 175


8.6

Summary 179


xiii

CONTENTS

9

Database-driven pages 181
9.1

When to use JSTL’s database support 183
When to use databases 183

9.2

Q

Direct access from JSP pages

183

Setting up a database connection with
<sql:setDataSource> 185
Caution against <sql:setDataSource> 188

9.3


Performing queries with <sql:query> 189
Performing a database query 190
Limiting the size of a query’s result

9.4

Reading a query’s results
197

191

Modifying data with <sql:update> 199
Simple uses of the <sql:update> tag
an <sql:update> tag 200

9.5

Q

199

Q

Measuring the effect of

Using <sql:param> with adjustable queries 201
Template queries 202 Safe, convenient parameters with
<sql:param> 202 Date parameters with <sql:dateParam> 205
Q


Q

9.6

Managing transactions with <sql:transaction> 206
The <sql:transaction> tag

10

207

Q

Transaction isolation

9.7

SQL example: a hit counter 211

9.8

Summary 213

Formatting and internationalization
10.1

210

215


Printing numbers with <fmt:formatNumber> 216
Basic usage of <fmt:formatNumber> 217 Different ways to specify
a value 218 Storing a number instead of printing it 219
Printing different types of numbers: percentages and currencies 219
Grouping digits together … or not 222 Controlling how many
digits print 223 More control: custom number patterns 226
Q

Q

Q

Q

10.2

Printing dates with <fmt:formatDate> 227
Differences from <fmt:formatNumber> 227 Printing times, dates,
or both 228 Printing longer or shorter dates and times 229
More control: custom date patterns 230
Q

Q

10.3

Reading numbers with <fmt:parseNumber> 232
Why you might want to parse numbers 233
How <fmt:parseNumber> works by default 233

Changing <fmt:parseNumber>’s parsing rules 235


xiv

CONTENTS

10.4

Reading dates with <fmt:parseDate> 236
How <fmt:parseDate> parses dates by default 236
Changing how <fmt:parseDate> parses dates 237

10.5

Overriding time zones with <fmt:timeZone> and
<fmt:setTimeZone> 238
How JSTL figures out time zones by default 239 Setting time
zones for individual tags 239 Long-lasting changes with
<fmt:setTimeZone> 240 Temporary changes with
<fmt:timeZone> 241
Q

Q

Q

10.6

Overriding locales with <fmt:setLocale>


242

How to identify locales 243 The parseLocale attribute for
<fmt:parseNumber> and <fmt:parseDate> 244
Q

10.7

Internationalizing text messages with <fmt:message>,
<fmt:param>,<fmt:bundle>, and <fmt:setBundle> 245
Using <fmt:message> 245 Loading a bundle family with
<fmt:bundle> and <fmt:setBundle> 247
Q

10.8

PART 3

11

Summary 248

JSTL IN ACTION ............................................ 249
Common tasks 251
11.1

Handling checkbox parameters 252
The HTML form 253 A simple checkbox handler
Handling some check boxes specially 256

Q

11.2

Accepting dates 257
The HTML form 258
reading the date 259

11.3

254

Q

Handling the form and

Handling errors 261
Ignoring the issue 262 Catching errors with <c:catch>
Passing errors to an error page 266
Q

11.4

263

Validating input 268
Different kinds of form validation 268 Tasks involved when
validating a form 269 A sample form validation 271
Q


Q

11.5

Summary 277


CONTENTS

12

Dynamic features for web sites 279
12.1

An online survey 280
What our survey looks like 281 Setting up the survey
database 281 Adding survey questions to pages 284
How the survey works 285
Q

Q

12.2

A message board 291
What our message board looks like 291 Setting up the message
database 293 Linking to appropriate message boards 294
How the message board works 295
Q


Q

12.3

13

Summary 300

Case study in building a web site
13.1

Managing the layout 303
A framework for channels 303

13.2

Q

Modular channels 305

Adding dynamic content 309
Including RSS channels 309

13.3

301

Q

Including other dynamic content 311


Registering users 313
Modifying the header 313 The registration form 314
Saving the registration 318 The user database 319
Q

Q

13.4

Authenticating users 320
Logging in users 320

13.5

Q

Some notes about authentication

Personalizing the site 322
Filling in a form automatically
chosen RSS feed 324

13.6

PART 4

14

321


322

Q

Displaying a

Summary 325

JSTL FOR PROGRAMMERS ........................... 327
Control and performance 329
14.1

Scripting elements and the JSTL rtexprvalue libraries 330
Warning against scripting expressions 331 JSTL’s dual
libraries 332 Scripting variables and <jsp:useBean> 333
Q

Q

14.2

Modifying properties with <c:set> 334

xv


xvi

CONTENTS


14.3

Advanced techniques for importing text 335
Representing imported text as a java.io.Reader
Character encoding 337

14.4

335

Advanced XML parsing and manipulation 338
XML data formats 338 Telling <x:parse> where a
document came from 340 Efficient parsing with
org.xml.sax.XMLFilter 341 Efficient transformations
with javax.xml.transform.Result 343
Q

Q

Q

14.5

Deciphering requests with <fmt:requestEncoding> 343

14.6

Exposing data to JSP pages 344
Saving data to a scope 344

Writing JavaBeans 347

14.7

Q

Exposing dynamic data structures 346

Configuring JSTL 349
Providing default information to JSTL tags 349 Managing
database access 352 Managing internationalization 354
Q

Q

14.8

Enforcing good page-authoring habits 355
Requiring script-free pages 356
Enumerating legal tag libraries 357

14.9

15

Summary 359

Using JSTL to develop custom tags 361
15.1


Developing and installing tag libraries 362
JSTL’s support for tag-handler developers 363 The tag-library
descriptor (TLD) 363 Installing and using a tag library 366
Q

Q

15.2

Developing conditional tags 366
A simple conditional tag 367 A conditional tag with
attributes 370 Integrating custom conditional tags with
standard tags 376 Using the expression language 377
Q

Q

Q

15.3

Developing iteration tags 378
A simple loop tag

15.4

Summary 387

379


Q

More advanced iteration tags

386


CONTENTS

A
B
C
D

JSTL reference

389

A.1

Expression language syntax 390

A.2

Core tag library 392

A.3

XML tag library 397


A.4

Database tag library 401

A.5

Formatting tag library 404

JSTL API (for developers)

409

B.1

Configuration variables 410

B.2

Conditions and loops 413

B.3

Interoperating with JSTL’s database tags 415

B.4

Using JSTL’s localization algorithms

Database tags and SQL


421

C.1

SQL and <sql:update> 422

C.2

SQL and <sql:query> 427

C.3

SQL miscellany 429

C.4

Summary 430

References and resources 433
D.1

JSP Standard Tag Library 434

D.2

XML-related references 435

D.3

Databases 435


D.4

Related standards 436

D.5

Miscellaneous references

index 439

437

417

xvii



preface
I originally got involved in creating the JSTL in Action ( JSTL) when Eduardo
Pelegri-Llopart at Sun noticed my emails on an Apache Jakarta mailing list and
thought I needed something to keep me busy.
This wasn’t strictly true—I already had quite enough on my plate—but I soon
found myself growing more and more interested in JSP tag libraries and the JSTL
effort. Soon, I was spending a good portion of my waking hours on it (and some
nonwaking hours, too).
If you like to design things, then helping to create a new standard and managing its reference implementation are thrilling tasks. Working with the Java Community Process means you meet bright, engaging people from all over the world,
and then spend hundreds of hours arguing with them about technical details. Like
most of my idiosyncratic pastimes (such as purchasing high-efficiency air filters or

watching the British Parliament on television), it might be hard to explain why
I’ve had so much fun with the Java Community Process—but it’s been a blast.
However, I don’t think my enjoyment of the process alone explains my
enthusiasm for JSTL. Rather, JSTL has a special appeal because its goal is to
make JSP, and web development in general, more accessible. Just as important,
JSTL’s design reminds me why I like Java in the first place. It’s maintainable,
based on thoughtful, careful principles, and easy to use. JSTL takes Java’s and
JSP’s advantages, packages them, and places them in your reach even if you
don’t know how to program yet.

xix


xx

PREFACE

This book will show you how to make the most of JSTL. It begins without
assuming you know anything more than HTML, and it gently introduces you to all
the principles you’ll need to produce flexible, powerful web pages. The goal of this
book isn’t to satisfy my own ego by showing you how subtle and tricky technology
can be, but instead to equip you to handle any JSTL-related issue that arises when
you produce real-world, dynamic web sites. If you read an example in this book
and think, “I didn’t realize it could be so easy,” then JSTL has done its job—and so
have I.


acknowledgments
Authors often wax sentimental when their books go to press. I think that’s
because writing computer books leads some people to turn to alcohol, quit their

jobs, and start wandering the wild.
My experience wasn’t anything like this. In fact, writing this book was a lot of
fun, and I’d do it all again (as soon as my wrists heal). Still, even a book that’s fun
to write isn’t produced in a vacuum, and it depends on the efforts and ideas of
many people.
I’d particularly like to thank Pierre Delisle, the specification lead for JSTL, for
his friendship, guidance, and trust. Pierre encouraged me to write this book, and
he’s also the one who asked me to lead the JSTL reference-implementation
effort. I used up all the French I know thanking Pierre in my last book, so for
now, I’ll stick with English and just say that it’s been fun and that I’ll miss our
long nights and email storms—at least, until JSTL 1.1!
I’d also particularly like to thank Marjan Bace for a wonderful author-publisher
relationship and for countless suggestions that made this book meaningfully better. With his sharp sense of the industry, I couldn’t have asked for a better guide.
Just as important, he’s kept things fun, and has set a great tone for all of Manning. After just one phone conversation with Marjan, I knew I’d found the publisher I wanted to work with.
The JSTL spec wouldn’t exist without the JSR-052 Expert Group. If all expert
groups were as good as this one, diplomats and ambassadors would use the Java
Community Process as an example of how to bring people together from around

xxi


xxii

ACKNOWLEDGMENTS

the world and solve difficult problems. Thanks in particular to the superb JSTL RI
team: Justy Horwat and Jan Luehe, with important contributions from Nathan
Abramson and Hans Bergsten (my competing JSP author!). I’m also indebted to the
JSP 1.3 spec leads, Eduardo Pelegri and Mark Roth, for making sure key JSP features were ready for JSTL on time.
Thanks to Ted Kennedy for coordinating the book’s reviews and managing an

amazing volume of useful and encouraging feedback from the likes of Monte Glenn
Gardner, Henri Yandell, Dean Riechman, Lance Andersen, Vimal Kansal, Phil
Hanna, Gal Shachor, Ian Jagger, Igor Fedulov, James McGovern, Rizwan Lodhi,
and James Strachan. Thanks to all of you—even the ones who objected to my offbeat humor. Thanks especially to Martin Cooper for his insightful technical proofing and to Tiffany Taylor for outstanding copyediting work.
Thanks to the production crew—particularly Mary Piergies, Syd Brown, and
Denis Dalinnik—and to Lianna Wlasiuk and Alex Garrett for some useful early
comments. Finally, thanks to Manning’s publicist, Helen Trimes, who might very
well be the reason you’re reading this book.
I also want to mention a few people from Yale. Thanks to my friend David
Davies for his generic-sounding name, which I’ve used in many examples throughout the book. Thanks also to my colleagues at Yale who, unlike David, didn’t leave
to go off to business school—particularly Andy Newman, Nick Rawlings, Susan
Bramhall, Howard Gilbert, and Peter Furmonavicius, for whom “Peter’s Junk-Mail
Service” from chapter 11 is named. The eccentric members of the
mailing list offered some useful minor comments too; I think they collectively had a
positive effect on about a dozen words in this manuscript. Thanks, guys.
Of course, I want to thank my parents. If they make it through chapter 1, I’ll be
delighted.
And thanks to you for reading all the way through the acknowledgments. But I
have to say, you’ll learn more from the book’s technical content. Get back to work!


about this book
Like JSTL, this book is aimed at both programmers and nonprogrammers.
Parts 1, 2, and 3 are accessible to page authors who start out with nothing more
than HTML. Part 4 is intended for Java programmers—and ambitious page
authors who want to learn more about how JSTL works behind the scenes.
In part 1, we look broadly at the Web and at two technologies that are important foundations to JSTL: JavaServer Pages ( JSP) and the Extensible Markup
Language (XML).
In part 2, we delve into JSTL’s depths. Chapters 3, 4, and 5 lay the necessary
groundwork by discussing JSTL’s expression language, conditions, and loops.

Chapters 6 through 10 discuss the more exciting features of JSTL: database
access, XML manipulation, text importing and formatting, and so forth.
In part 3 (chapters 11, 12, and 13), we look at progressively more complete and
integrated examples of JSTL in action. We start with common, stand-alone tasks
and move to an example of organizing an entire site—a web portal—using JSTL.
Finally, part 4 discusses how to configure JSTL, integrate Java code, and even
write custom tags using JSTL’s API.
The appendices contain reference material. Appendix A is a brief summary of
all of JSTL’s tags. Appendix B lists JSTL’s API and goes into detail about some of
its advanced features. Appendix C describes the basics of SQL to help you follow
some of the book’s examples, and appendix D lists online and printed references.

xxiii


xxiv

ABOUT THIS BOOK

How to approach the book
If you’re a web-page author who knows HTML, you’ll probably want to start at the
beginning. Chapters 1 and 2 will be particularly useful to you, and you can read the
rest of the book in order, stopping somewhere around chapter 14 if the material
becomes less interesting to you. If you already know JavaScript, pay special attention to chapter 3, because you’ll need to master the details of JSTL’s expression language. JavaScript won’t help you produce dynamic server-side logic in this
environment. If you don’t know SQL, appendix C will help you follow the book’s
database examples.
If you’re an experienced Java programmer looking to master JSTL in order to
use or teach it, you can probably skip part 1. You might want to begin by focusing
on the expression language in chapter 3. Chapters 4 and 5 will be a breeze, but the
rest of part 2 should be useful in orienting you to JSTL’s tag-set. The examples in

part 3 will be useful, and part 4 is specially intended for you. Also, appendix B is
both a thorough reference and an indispensable introduction to some of JSTL’s
advanced features.
If you have a background in JSP but aren’t familiar with Java, then parts 2 and 3
will be particularly useful to you. Also, the beginning of chapter 14—integrating
JSTL with scriptlets—might be helpful.
In general, the book gets more advanced as it moves forward. Most readers will
gain less by reading the book backward (but if you find any interesting hidden messages that way, be sure to let me know).

Conventions
By and large, the book is self-explanatory. I’ve followed a few conventions throughout the book that should help illuminate some material; a general convention suggests that I list them here. They include:
Q
Boldface type
In code listings, I use boldface type to differentiate dynamic code ( JSTL
tags) from static text (including HTML tags). This distinction is useful because
they look the same on the surface, so they can easily blur, especially late at
night. Also, a few examples use a JSTL tag within an HTML tag, and boldface
is helpful to make sure the JSTL tag stands out.
Q

Other type styles
I occasionally use italics when introducing a term I want you to remember—
or a word that I’d accompany with a bang on the table if I were speaking to
you in person (and if there were a table present). Courier font marks tag


×