JSTL : Practical Guide For JSP Programmers

2y ago
117 Views
5 Downloads
8.61 MB
250 Pages
Last View : 1d ago
Last Download : 3m ago
Upload by : Evelyn Loftin
Transcription

JSTLPractical Guide for JSP Programmers

The Morgan Kaufmann Practical Guides SeriesSeries Editor, Michael J. DonahooJSTL: Practical Guide for JSP ProgrammersSue SpielmanJSP: Practical Guide for Java ProgrammersRobert J. BrunnerJava: Practical Guide for ProgrammersZbigniew M. SikoraThe Struts Framework: Practical Guide for Java ProgrammersSue SpielmanMulticast Sockets: Practical Guide for ProgrammersDavid Makofske and Kevin AlmerothTCP/IP Sockets in Java: Practical Guide for ProgrammersKenneth L. Calvert and Michael J. DonahooTCP/IP Sockets in C: Practical Guide for ProgrammersMichael J. Donahoo and Kenneth L. CalvertJDBC: Practical Guide for Java ProgrammersGregory D. SpeegleFor further information on these books and for a list of forthcoming titles, please visit ourwebsite at http://www.mkp.com/practical

JSTLPractical Guide forJSP ProgrammersSue SpielmanSwitchback Software LLCAMSTERDAM BOSTON HEIDELBERG LONDONNEW YORK OXFORD PARIS SAN DIEGOSAN FRANCISCO SINGAPORE SYDNEY TOKYOMorgan Kaufmann is an imprint of Elsevier

This book is printed on acid-free paper.Senior Editor:Developmental Editor:Publishing Services Manager:Senior Project Manager:Project Management:Composition:Cover Design:Printer:Rick AdamsKaryn JohnsonSimon CrumpAngela G. DooleyKeywordCEPHACate BarrMaple-VailCopyright 2004, Elsevier Science (USA)All rights reserved.No part of this publication may be reproduced or transmitted in any form or by any means,electronic or mechanical, including photocopy, recording, or any information storage andretrieval system, without permission in writing from the publisher.Designations used by companies to distinguish their products are often claimed as trademarks orregistered trademarks. In all instances in which Morgan Kaufmann Publishers is aware of a claim,the product names appear in initial capital or all capital letters. Readers, however, should contactthe appropriate companies for more complete information regarding trademarks and registration.In no event shall the publisher or the author be liable for any direct, indirect, special, consequential,or inconsequential damages. No warranties are expressed of implied, including warranties ormerchantability or fitness for a particular purpose.Permissions may be sought directly from Elsevier’s Science & Technology RightsDepartment in Oxford, UK: phone: ( 44) 1865 843830, fax: ( 44) 1865 853333, e-mail:permissions@elsevier.com.uk. You may also complete your request on-line via the Elsevierhomepage (http://elsevier.com), by selecting “Customer Support” and then “Obtaining Permissions.”Morgan KaufmannAn imprint of Elsevier Science340 Pine Street, Sixth Floor, San Francisco, California 94104-3205, USAhttp://www.mkp.comLibrary of Congress Catalog Card Number: 2003107479International Standard Book Number: 0-12-656755-7Printed in the United States of America031 2 3 4 5

Act mindfullyAccept entirelyMove stronglyThink softlySpeak beautifullyLive simplyLove completelyAnonymous

This Page Intentionally Left Blank

Dedicated to my familyMommasita, Papar, Liz, Ken, Randi, Ryan, Christopher, Bev, and Sid

This Page Intentionally Left Blank

ContentsPreface1xviiIntroduction11.1What Exactly Is the JSTL? 11.2Why a JSP Standard Tag Library? 21.3Why Now? 21.4Why You Really Want to Use the JSTL 31.5The Need for Encapsulation 31.6Functional Overview 31.7JSTL Tag Libraries 41.8Getting Ready to Use the JSTL 61.9The Road to the JSTL 61.9.1 Dynamic vs. Static Content 61.9.2 Using Dynamic Content 71.9.3 Using Dynamic Web Features 71.9.4 Server-Side Processing 71.10 Servlets to the Rescue 81.11 Hello My Friend Servlet 91.12 JavaServer Pages 121.13 When a JSP, When a Servlet? 141.14 Evolving JSP 141.15 Custom Actions in Action 151.15.1 Why Use a Custom Action 15ix

xContents 1.15.2 Hello My Friend Using Custom Actions 161.15.3 The TLD File 161.15.4 The Tag Handler 181.16 The Power of Tag Libraries 191.16.1 Need for a Tag Library 201.17 Making Life Easier, JSTL in Action 202JSTL Basics232.1Environment Setup 232.2Using the Book Examples 242.3JSP Scopes 252.4JSTL Scoped Variables 272.4.1 Var and Scope Attributes 272.4.2 Variable Visibility 282.5Dynamic and Static Attributes 292.6Handling Errors and Exceptions 292.7Action Body Content 312.8Configuration Settings 322.9The Config Class 332.10 Summary 3434Using the Expression Language353.1Implicit Objects Available in the EL 363.2Accessing Data Structures 373.3EL Operators 383.3.1 Relational Operators 383.3.2 Other Operators 383.3.3 Using Operators 383.4Automatic Type Conversion 403.5Default Values 413.6Summary 42Working with the Core Actions434.1Writing Output to the JspWriter 434.2Setting Variables 454.3Removing Variables 49

4.4Using c:catch 504.4.1 Handling Exceptions 514.5Decisions, Decisions, Decisions—Conditional Actions 524.5.1 Simple Conditional 534.5.2 Mutually Exclusive Conditionals 544.5.3 Creating Custom Logic Actions 564.6Handling Iterators 564.6.1 c:forEach 574.6.2 Paging through a Large Collection 594.6.3 Looping with a Collection 634.6.4 Tokenizing Data Using c:forTokens 674.7URL-Related Actions 714.7.1 c:import 714.7.2 c:url 734.7.3 Creating and Using Dynamic Links 734.7.4 c:param 744.7.5 c:redirect 754.8Untangling the Web We Weave 764.8.1 The Power of c:import 764.8.2 c:import and the Composite View Pattern 764.8.3 Storing Imported Content 804.8.4 Using Character Encoding 824.9Redirecting 834.10 Summary 845ContentsWorking with the XML Actions855.1Overview of Supporting Technologies 855.2eXtensible Markup Language (XML) 865.2.1 Using XML Files for Data Storage 875.2.2 XML APIs 875.3eXtenstible Stylesheet Language (XSL) 885.3.1 Allowing for Transformation 885.3.2 XSL Languages 895.4XML Path Language (XPath) 905.4.1 Library Functions 915.5Variable Mappings 915.6Using the Select Attribute 935.7Accessing Resources 935.7.1 Node Types 945.7.2 Node Functions 94xi

xiiContents 5.8eXtensible Stylesheet Language Transformation (XSLT) 955.8.1 XSLT Namespace 955.9Parsing XML Documents 965.9.1 x:parse Action 965.9.2 Filtering 975.9.3 Using the Advanced x:parse Attributes 995.10 Using x:out and x:set 1005.10.1 x:out Action 1005.10.2 x:set Action 1015.11 x:set and x:out in Action 1015.12 Using XML Documents to Determine Flow Control 1025.12.1 x:if Action 1035.12.2 Using x:if 1045.12.3 x:choose , x:when , and x:otherwise Actions 1055.13 Going Loopy with x:forEach 1065.13.1 Nested forEach Loops 1075.14 XML Transformation Actions 1105.14.1 x:transform Action 1105.15 Transforming Content 1115.16 Providing Parameters to Transformations 1135.16.1 x:param Action 1135.16.2 Performing Multiple Transformations 1155.17 Summary 1156Working with the Internationalization and Formatting Actions6.1Locales 1186.1.1 Internationalization vs. Localization 1186.2Why be Language Independent? 1196.3Localizing an Application Using Resource Bundles 1196.4Types of I18N Architectures 1206.5First, the fmt:message Action 1216.6Localization Context 1226.7Localization Context Sample 1236.8Preferred Locales 1236.8.1 Setting the Preferred Locales 1246.9Formatting Locales 1246.10 How Resource Bundles are Decided 1256.10.1 Resource Bundle Lookup Differences 127117

Contents6.11 Resource Bundle Lookup Samples 1296.12 Using the LocaleSupport Class 1296.13 Setting and Using Locales 1306.13.1 fmt:setLocale Action 1306.13.2 Having a Fallback Locale 1316.14 Using Messages and Resource Bundles 1336.14.1 fmt:bundle Action 1346.14.2 fmt:setBundle Action 1346.14.3 fmt:message Action 1356.14.4 fmt:param Action 1356.15 Setting the Resource Bundle for fmt:message 1366.16 Adding a parameter to fmt:message 1386.17 Formatting Actions 1396.17.1 Determining the Time Zone 1406.17.2 fmt:timeZone Action 1406.17.3 fmt:setTimeZone Action 1406.18 Setting and Using Time Zones 1416.19 Working with Timestamps 1436.20 Formatting and Parsing Timestamps 1436.20.1 fmt:formatDate Action 1436.20.2 fmt:parseDate 1446.20.3 Customizing the Format 1476.21 Using and Parsing Timestamps 1486.22 Working with Numbers 1506.22.1 fmt:formatNumber Action 1516.22.2 fmt:parseNumber Action 1526.22.3 Formatting Numbers 1536.22.4 Parsing Numbers 1576.23 Encoding the Client Response 1586.24 Summary 1607SQL Tag Library Using the SQL Actions1617.1The Available SQL Actions 1627.2Working with the Data Source 1637.2.1 sql:setDataSource 1637.3Configuring a Data Source 1647.4Using a Data Source 1657.5Maxrows Configuration Setting 1657.6Configuring and Using a Data Source 166xiii

xivContents 7.7How to Modify Data 1677.7.1 sql:update Action 1687.7.2 How to Use var with sql:update 1697.8Interfaces and Classes 1707.8.1 Result Interface 1707.8.2 SQLExecutionTag Interface 1707.8.3 ResultSupport Class 1727.9Finding What You Need with sql:query 1727.9.1 sql:query Action 1737.10 Passing Parameters to SQL Statements 1747.10.1 Dealing with Date Parameters 1777.11 Working with Result Sets 1777.11.1 Accessing Rows and Columns 1787.11.2 Using Result Set Metadata 1807.12 Dealing with Transactions 1817.12.1 Words of Caution 1817.13 sql:transaction Action 1827.14 How to Use sql:transaction 1827.15 Summary 1857.16 Conclusion 1868JSTL Quick Reference1878.1Expression Language Syntax 1878.1.1 Literals 1888.1.2 “[ ]” and “.” Operators 1888.1.3 Arithmetic Operators 1888.1.4 Relational Operators 1908.1.5 Logical Operators 1918.1.6 Empty Operator 1918.1.7 Operator Precedence 1928.1.8 Reserved Words 1928.1.9 Coercion Rules 1928.1.10 Accessing Named Variables 1948.1.11 Implicit Objects 1958.2Configuration Settings 1968.3Core Tag Library 1988.3.1 Tag Library URI 1998.3.2 General Purpose Actions 1998.3.3 Conditional Actions 200

8.3.48.3.5Iterator Actions 202URL Related Actions 2048.4XML Tag Library 2068.4.1 Tag Library URI 2068.4.2 XML Core Actions 2068.4.3 XML Flow Control 2088.4.4 Iterator Actions 2098.4.5 Transformation Actions 2108.5SQL Tag Library 2118.5.1 Tag Library URI 2118.5.2 Actions 2118.6I18N Tag Library 2158.6.1 Tag Library URI 2158.6.2 Internationalization Actions 2158.6.3 Formatting Actions 220Index225Contentsxv

This Page Intentionally Left Blank

PrefaceAs a JSP developer, you are probably always looking for ways to improve your JSP pageauthoring. The JSP Standard Tag Library (JSTL) will provide you with a plethora of usefulactions that you can start taking advantage of today. It will allow you to focus on the truepresentation features of your pages, while providing a comprehensive cover for commontasks that page authors continually run into. My goal in writing this book is to get you upto speed as quickly as possible on all that is available in the JSTL and how to apply thatknowledge to your daily page authoring. You’ll be amazed at how much cleaner your pageswill appear and how much better you’ll feel about them. Just like when you finally cleanout of your closet the 10-year-old t-shirts that you thought you couldn’t live without.What’s to ComeFirst we’ll look at how we arrived at the need for the JSTL and what it can provide. In theintroduction chapters, I’ll provide answers to some initial questions about what customtags are and what custom tag libraries look like and what types of actions are availablein the JSTL. The next few chapters include JSTL basics, the JSTL layout and how to workwith the expression language. We’ll then go into each of the functional areas, and thecustom actions provided by each, and work through detailed samples for each and everyaction. We will focus on the details of using each of the various tags as well as the varioussituations that each tag can be applied to. Plenty of code samples are included.I hope that, provided with the quick reference for all of the tags and attributes contained in JSTL 1.0, you’ll be able to use this reference during your JSP development andflip to the appropriate page for specific tag information. I take the “practical” in the titleof this book seriously.xvii

xviiiPreface The Code SamplesAll of the code samples you will encounter in this book are provided in a sample download.I wanted to cover all of the attributes and features of each action. Each and every action hasan accompanying sample file that you can reference according to the chapter in which itappears. These samples should give you an excellent reference for how to use the actionsso that you can go off and utilize them in your applications.You can access the download from http://www.mkp.com/practical/jstl or fromhttp://www.switchbacksoftware.com. I am utilizing the reference implementation ofthe JSTL from the Jakarta Tablib standard project. The .jar files required for theJSTL are provided with the download; however, you can visit the Jakarta site oc/intro.html for the latest informationon the available reference implementation. This book uses the JSTL 1.0.3 referenceimplementation along with Tomcat 5.0.Tomcat 5.0 is the next major release of Tomcat. It builds on the Tomcat 3.3 andTomcat 4.1.x code base. The 5.0 release implements the JSP 2.0 and Servlet 2.4 specifications that will be available in the next major release of the J2EE 1.4 platform. At the time ofthis writing, Tomcat 5.0 is still in Alpha. Taking that into consideration, I have also run thecode samples on Tomcat 4.1.20, so if you are on that version, you should have no problem.The Tomcat 4.1.x release implements the JSP 1.2 and the Servlet 2.3 specifications.When J2EE 1.4 is released there should be some minor enhancements to the JSTL andthe revision will become v1.1. These enhancements include support for some of the functionality that will be available in the expression language in JSP 2.0. However, by readingthis book, you will be ahead of the game because you’ll already have a full understanding of the expression language (EL) and how to use it. I suggest that, if you are goingto be working with JSP 2.0, you take a few minutes to examine the small changes in theexpression language so that you can take full advantage of it.Specifications to Be Familiar WithLike any of the web technologies that developers work with, there is always an overabundance of additional specifications with which we must become familiar. Since theJSTL covers different areas of functionality, there are more than a few specs that youprobably want to be aware of, or explore, in more detail. Don’t worry; you don’t have tobe an expert on any of them. However, this book assumes that you are at least familiar ata high level with the topics covered in the specifications listed in Table 0.1.AcknowledgmentsThis project seemed to take on a life of its own, but I am glad that it found its roots. Eachtime I take on a new book project, I conveniently forget how much time, energy, thought,

SpecificationLocationJavaServer Pages (JSP)Java Servlet TechnologyJava 2 Platform, Standard EditionJava 2 Platform, Enterprise EditionJavaBeansJDBCJava Technology and XMLXPath specificationXML home page at W3CHTML home page at W3CXML.org home //www.xml.orgPrefacexixTable 0.1: Related specifications.and debugging go into it. Similarly to what I do when I’m riding my bike up a long steepmountain pass, I typically say “How hard can it be?”, and then just start. It is only whenyou start that it all comes back at you. It’s then that you realize that not only does it takea major time commitment on your own part, but also that it relies on a number of peoplewhose support and work bring the project to life.Thanks (again) to Karyn Johnson and Rick Adams for bringing me on board for anotherbook in the Practical Guide Series. My sincere thanks to all of the proposal and technical reviewers who were an absolute stellar bunch. They include: Thomas Paul, AnthonyIkeda, Tom Marrs, John Raley, Matt Houser, Pierre Delisle, Ireno Marchenko, and GrandinHammell. The technical review comments inspired me to completely reorganize this bookfrom its orginial form. As I said, this project has a life of its own and you just have togo with it sometimes. The comments and suggestions that I received as input from thereviewers were invaluable and raised the bar on the book for all readers.Thank you to the production staff at Morgan Kaufmann and Keyword who really areindustry top notch. They include: Maureen Allen and Angela Dooley.Thanks (again) to Pierre Delisle, the JSTL specification lead at Sun Microsystems, foralways promptly answering my email questions.I’d like to acknowledge my grandparents, for while they aren’t physically on thisplanet any more, they are in my thoughts every day. I know that they’d be beaming holdingthis book. I miss you both.And last, but certainly not least, thank you to Elizabeth for just about everything.Your assistance, patience, and understanding are never overlooked or under-appreciated.

This Page Intentionally Left Blank

cha pter1IntroductionThe fact that you are holding this book in your hands indicates that you are notonly intrigued by the world of the web, but you are actually shaping it. As a developeryou either have built, or are about to build, some form of web application. This book isfocused on how to get the most out of the JSP Standard Tag Library, also referred to as theJSTL, when you are building your web applications.This first, introductory chapter answers the basic questions surrounding what theJSTL is, why using it will make your life easier, how it deals with dynamic content, andwhy a JSTL is needed. I make no bones about it, when you’re done with this chapter youshould be raring to start using the JSTL.1.1What Exactly Is the JSTL?JSTL is the JSP Standard Tag Library. The JSTL came about under JSR-52 of the Java Community Process (JCP). The specification can be found at http://jcp.org/jsr/detail/52.jsp. JSR-52covers the creation of a standard tag library for JavaServer Pages and allows this libraryto be available to all compliant JSP containers. These tag libraries provide a wide rangeof custom action functionality that most JSP authors have found themselves in need of inthe past. Having a defined specification for how the functionality is implemented meansthat a page author can learn these custom actions once and then use and reuse them onall future products on all application containers that support the specification. Using theJSTL will not only make your JSPs more readable and maintainable, but will allow you toconcentrate on good design and implementation practices in your pages. We can finallytake the “custom” out of custom action and replace it with “standard.” No more creating1

2Chapter 1: Introduction your own iteration action for the tenth time. Additionally, your favorite Integrated Development Environment (IDE) that supports JSP authoring will now support these standardactions and can assist the JSP page author in rapid development.So to sum up how the JSTL got here, an expert group was tasked with creating customactions that are valuable to a range of JSP authors and developers, and that is exactly whatthey created.1.2Why a JSP Standard Tag Library?We have answered the “what is the JSTL” question, but let’s answer the “why” question.Why a JSP standard tag library and, for that matter, why now? The answer to both is quitesimple: because writing your own custom actions is a time consuming pain.With the introduction of JSP 1.1, there existed a standard mechanism for the creationof tag libraries. Initially, we all referred to this mechanism as custom tags, now we refer toit as custom actions. That’s why we still see the collection of actions called Tag Libraries asopposed to Action Libraries. Otherwise, we’d be referring to the JSAL instead of the JSTL.JSTL just sounds better. Both terms, custom tags and custom actio

The Morgan Kaufmann Practical Guides Series Series Editor, Michael J. Donahoo JSTL: Practical Guide for JSP Programmers Sue Spielman JSP: Practical Guide for Java Programmers . 2.2 Using the Book Examples 24 2.3 JSP Scopes 25 2.4 JSTL Scoped Variables 27 2.4.1

Related Documents:

JSP page is a simple web page which contains the JSP elements and template text. The template text can be scripting code such as Html, Xml or a simple plain text. Various Jsp elements can be action tags, custom tags, JSTL library elements. These JSP elements are responsible for generating dynamic contents. Pure Servlet

JSF has nothing to do with JSP per se. JSF works with JSP through a JSP tag library bridge. However, the life cycle of JSF is very different from the life cycle of JSP. Facelets fits JSF much better than JSP because Facelets was designed with JSF in mind, whereas integrating JSF and JSP has

1 Difference between Servlets and JSP 2 Basic JSP Architecture 3 Life Cycle of JSP 4 JSP Tags and Expressions 5 Scriptlets, Declarations, Expressions & Directives 6 Action Tags and Implicit Objects 7 JSP to Servlets & Servlets to JSP . 11 St

Podemos editar más de una clase o página JSP en la ventana de edición, cada una en su propio panel, como se muestra en la figura 4.13 en la que tenemos en la ventana de edición de NetBeans dos páginas JSP: index.jsp y control.jsp. Las pestañas en la parte superior nos permiten seleccionar la clase o página JSP que se desea editar. Figura .

The welcome page (index.jsp) presents the user with a simple HTML form.When a browser requests index.jsp, the JSTL code within the page initiates a query on MyNewDatabase. It retrieves data from the Subject database table, and inserts it into to the page before it is sent to the browser. Table TWO-TIER Architecture: a Java web application communicates directly with a

Bruksanvisning för bilstereo . Bruksanvisning for bilstereo . Instrukcja obsługi samochodowego odtwarzacza stereo . Operating Instructions for Car Stereo . 610-104 . SV . Bruksanvisning i original

JSP i About the Tutorial Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.

Waterhead 1003 1346 St James 1041 1393 Chadderton South 1370 964 Failsworth West 1596 849 Chadderton North 2038 791 Chadderton Central 2096 695 Failsworth East 2234 643 Shaw 2295 893 Royton South 3008 628 Royton North 3297 808 Crompton 3858 510 Saddleworth West and Lees 3899 380 Saddleworth North 5892 309 Saddleworth South 6536 260 3.3 There is a wealth of evidence to suggest links between .