Home
The J2EE™ Tutorial
Contents
1. 1 Distributed Multitiered Applications 2 J2EE Components 3 J2EE Clients 4 Web Components 6 Business Components 6 Enterprise Information System Tier 8 J2EE Containers 8 Container Services 8 Container Types 9 Web Services Support 10 XML 11 SOAP Transport Protocol 11 WSDL Standard Format 12 UDDI and ebXML Standard Formats 12 Packaging Applications 12 Development Roles 14 J2EE Product Provider 14 Tool Provider 14 Application Component Provider 15 Application Assembler 15 Application Deployer and Administrator 16 J2EE 1 4 Platform APIs 16 Enterprise JavaBeans Technology 17 Java Servlet Technology 18 JavaServer Pages Technology 18 vii o se J2EETutorial book Page viii Thursday June 3 2004 10 26 AM viii CONTENTS Java Message Service API 18 Java Transaction API 18 JavaMail API 18 JavaBeans Activation Framework 19 Java API for XML Processing 19 Java API for XML Based RPC 19 SOAP with Attachments API for Java 20 Java API for XML Registries 20 J2EE Connector Architecture 20 JDBC API 21 Java Naming and Directory Interface 21 Java Authentication and Authorization Service 22 Simplified Systems Integration 22 Sun Java System Application Server Platform Edition 8 23 Technologies 24 Tools 25 Starting and Stopping the Application Server 25 Starting the Admin Console 27 Starting the deploytool Utility 27 Starting and Stopping the PointBase Database Server 28 Debugging J2EE Application
2. se J2EETutorial book Page 712 Thursday June 3 2004 10 26 AM 712 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES the page Duke s Bookstore does not use any ActionListener implementations Here is one of the commandLink tags on the chooselocale jsp page changed to reference an ActionListener implementation rather than a backing bean method lt h commandLink id NAmerica action bookstore gt lt f actionListener type listeners LocaleChange gt lt h commandLink gt The type attribute of the actionListener tag specifies the fully qualified class name of the ActionListener implementation When this tag s component is activated the component s decode method or its associated Renderer automatically queues the ActionEvent implementation associated with the specified ActionListener implementation to the component Using the Standard Validators JavaServer Faces technology provides a set of standard classes and associated tags that page authors and application developers can use to validate a compo nent s data Table 18 7 lists all the standard validator classes and the tags that allow you to use the validators from the page Table 18 7 The Validator Classes Validator Class Tag Function Checks whether the local value of a component is within a certain range The value must be floating point or convertible to floating point DoubleRangeValidator validateDoubleRange Checks whether the length of a co
3. USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES The following tag registers a hypothetical validator on a component using a validator tag and referencing the ID of the validator lt h inputText id name value 4 CustomerBean name size 10 gt lt f validator validatorId customValidator gt lt h inputText gt Using a Custom Component Using a custom component on a page is similar to using a custom validator except that custom validator tags must be nested inside component tags In order to use the custom component in the page you need to declare the tag library that defines the custom tag that render the custom component This is explained in Using Custom Objects page 723 The Duke s Bookstore application includes a custom image map component on the chooselocale jsp page This component allows you to select the locale for the application by clicking on a region of the image map lt h graphicImage id mapImage url template world jpg alt bundle chooseLocale usemap worldMap gt lt bookstore map id worldMap current NAmericas immediate true action bookstore actionListener 1ocaleBean chooseLocaleFromMap gt lt bookstore area id NAmerica value NA onmouseover template world_namer jpg onmouseout template world jpg targetImage mapImage gt lt bookstore area id France value fraA onmouseover template world_france jpg onmouseout template world jpg target
4. Registers a DateTime converter Data conversion tags convertDateTime instance on the parent component Registers a Number converter instance convertNumber on the parent component Signifies a nested component that has a Facet tag special relationship to its enclosing tag se J2EETutorial book Page 679 Thursday June 3 2004 10 26 AM Table 18 1 The jsf_ Tag Categories Localization tag USING THE CORE TAGS core Tags Continued Tags Functions loadBundle Specifies a ResourceBundle that is exposed as a Map Parameter substitution tag Substitutes parameters into a Message Format instance and adds query string name value pairs to a URL Tags for representing items in a list selectItem Represents one item in a list of items in a UISelectOne or UISelectMany component selectItems Represents a set of items in a UISelec tOne or UISelectMany component Container tag subvi ew Contains all JavaServer Faces tags in a page that is included in another JSP page containing JavaServer Faces tags Validator tags validateDoubleRange Registers a DoubleRangeValidator on a component validateLength Registers a LengthValidator ona component validateLongRange Registers a LongRangeValidator on a component validator Registers a custom validator on a com ponent Output tag verbatim Generates a UIOutput component that gets it
5. bookDBAO books var book gt The stylesheet that defines this class is stylesheet css which is included in the application For more information on defining styles please see the Cascad ing Style Sheets Specification at http ww w3 org Style CSS The value and binding Afiributes A tag representing a component defined by UIOutput or a subclass of UIOutput uses value and binding attributes to bind its component s value or instance to an external data source Binding Component Values and Instances to External Data Sources page 714 explains how to use these attributes The UlForm Component A UIForm component is an input form that has child components representing data that is either presented to the user or submitted with the form The form tag encloses all the controls that display or collect data from the user Here is an example lt h form gt other faces tags and other content lt h form gt The form tag can also include HTML markup to lay out the controls on the page The form tag itself does not perform any layout its purpose is to collect data and to declare attributes that can be used by other components in the form A page o 683 4 se J2EETutorial book Page 684 Thursday June 3 2004 10 26 AM 684 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES can include multiple form tags but only the values from the form that the user submits will be included in the postback The UlCol
6. e XML standards Appendix B e HTTP Overview Appendix C e J2EE Connector Architecture Appendix D About the Examples This section tells you everything you need to know to install build and run the examples Required Software Tutorial Bundle The tutorial example source is contained in the tutorial bundle which is distrib uted on the accompanying CD ROM After you have installed the tutorial bundle the example source code is in the lt INSTALL gt j2eetutorial14 examples directory with subdirectories for each of the technologies discussed in the tutorial Application Server The Sun Java System Application Server Platform Edition 8 is targeted as the build and runtime environment for the tutorial examples To build deploy and run the examples you need a copy of the Application Server and the Java 2 Software Development Kit Standard Edition J2SE SDK 1 4 2_04 or higher o 18 se J2EETutorial book Page xli Thursday June 3 2004 10 26 AM ABOUT THE EXAMPLES The Application Server and J2SE SDK are contained in the J2EE 1 4 SDK which is distributed on the CD ROM accompanying the tutorial Application Server Installation Tips In the Admin configuration pane of the Application Server installer e Select the Don t Prompt for Admin User Name radio button This will save the user name and password so that you won t need to provide them when performing administrative operations with
7. a b C d Select the bookstore6 WAR from the tree Select the Context tabbed pane and click Add Enter javax faces STATE_SAVING_METHOD in the Coded Parameter field Enter client in the Value field Set preludes and codas for all JSP pages a b C Select the JSP Properties tab Click Add Enter bookstore6 in the Name field o 18 se J2EETutorial book Page 675 Thursday June 3 2004 10 26 AM 11 12 13 14 15 16 17 18 19 THE EXAMPLE JAVASERVER FACES APPLICATION Click Add URL Enter jsp in the URL Patterns field Click Edit Preludes Click Add Enter template prelude jspf Click OK Click Edit Codas Click Add Enter template coda jspf m Click OK PR mo A j i o P Add the listener class 1isteners ContextListener described in Han dling Servlet Life Cycle Events page 441 a Select the Event Listeners tab b Click Add c Select the listeners ContextListener class from the drop down menu in the Event Listener Classes pane Add a resource reference for the database a Select the Resource Ref s tab Click Add Enter jdbc BookDB in the Coded Name field Accept the default type javax sql DataSource Accept the default authorization Container Accept the default selected Shareable Enter jdbc BookDB in the JNDI Name field of the Sun specific Set tings frame Select File Save m mo Bo gp Deploy the appli
8. 1162 Administered Objects 1163 Connections 1165 Sessions 1165 Message Producers 1166 Message Consumers 1167 Messages 1169 Exception Handling 1172 Writing Simple JMS Client Applications 1173 A Simple Example of Synchronous Message Receives 1174 A Simple Example of Asynchronous Message Consumption 1183 Running JMS Client Programs on Multiple Systems 1187 Creating Robust JMS Applications 1191 Using Basic Reliability Mechanisms 1193 Using Advanced Reliability Mechanisms 1200 Using the JMS API in a J2EE Application 1212 Using Session and Entity Beans to Produce and to Synchronously Receive Messages 1212 Using Message Driven Beans 1214 Managing Distributed Transactions 1216 Using the JMS API with Application Clients and Web Components 1219 Further Information 1220 18 se J2EETutorial book Page xxx Thursday June 3 2004 10 26 AM XXX CONTENTS Chapter 34 J2EE Examples Using the JMS API 1221 A J2EE Application That Uses the JMS API with a Session Bean 1222 Writing the Application Components 1223 Creating and Packaging the Application 1225 Deploying the Application 1229 Running the Application Client 1230 A J2EE Application That Uses the JMS API with an Entity Bean 1231 Overview of the Human Resources Application 1231 Writing the Application Components 1232 Creating and Packaging the Application 1235 Deploying the Application 1237 Running the Application Client 1238 An Application Example That Consumes Message
9. 219 Handling Modifications 228 Finishing Up 228 Creating and Manipulating a DOM 228 Obtaining a DOM from the Factory 228 Normalizing the DOM 231 Other Operations 233 Finishing Up 237 se J2EETutorial book Page xii Thursday June 3 2004 10 26 AM xii Chapter 7 CONTENTS Validating with XML Schema 237 Overview of the Validation Process 237 Configuring the DocumentBuilder Factory 238 Validating with Multiple Namespaces 239 Further Information 243 Extensible Stylesheet Language Transformations 245 Introducing XSL XSLT and XPath 246 The JAXP Transformation Packages 246 How XPath Works 247 XPath Expressions 247 The XSLT XPath Data Model 248 Templates and Contexts 249 Basic XPath Addressing 249 Basic XPath Expressions 250 Combining Index Addresses 251 Wildcards 251 Extended Path Addressing 252 XPath Data Types and Operators 252 String Value of an Element 253 XPath Functions 253 Summary 257 Writing Out a DOM as an XML File 257 Reading the XML 258 Creating a Transformer 259 Writing the XML 262 Writing Out a Subtree of the DOM 263 Summary 264 Generating XML from an Arbitrary Data Structure 264 Creating a Simple File 265 Creating a Simple Parser 267 Modifying the Parser to Generate SAX Events 269 Using the Parser as a SAXSource 275 Doing the Conversion 278 Transforming XML Data with XSLT 278 Defining a Simple lt article gt Document Type 279 Creating a Test Document 281 Writing an XSLT Transform 282 Processing th
10. 9999 9999 9999 gt lt h inputText gt lt h message styleClass validationMessage for ccno gt lt h panelGrid gt This panelGrid tag is rendered to a table that contains controls for the customer of the bookstore to input personal information This panelGrid uses stylesheet tags classes to format the table The CSS classes are defined in the stylesheet css file in the lt INSTALL gt j2eetutorial14 examples web bookstore6 web directory The 1ist header definition is list header background color FFFFFF color 000000 text align center Because the panelGrid tag specifies a headerClass the panelGrid must con tain a header The example panelGrid tag uses a facet tag for the header Fac ets can have only one child and so a panelGroup tag is needed if you want to group more than one component within a facet Because the example panel Grid tag has only one cell of data a panelGroup tag is not needed A panelGroup tag can also be used to encapsulate a nested tree of components so that the tree of components appears as a single component to the parent component The data represented by the nested component tags is grouped into rows accord ing to the value of the columns attribute of the panelGrid tag The columns attribute in the example is set to 3 and therefore the table will have three col umns In which column each component is displayed is determined by the order that the component is listed on the page m
11. Deactivating Expression Evaluation 490 Using Expressions 490 Variables 491 Implicit Objects 492 Literals 493 Operators 493 Reserved Words 494 Examples 494 Functions 496 JavaBeans Components 497 JavaBeans Component Design Conventions 497 Creating and Using a JavaBeans Component 499 Setting JavaBeans Component Properties 500 Retrieving JavaBeans Component Properties 502 Using Custom Tags 502 Declaring Tag Libraries 503 Including the Tag Library Implementation 505 Reusing Content in JSP Pages 506 Transferring Control to Another Web Component 507 jsp param Element 508 Including an Applet 508 Setting Properties for Groups of JSP Pages 510 Further Information 513 Chapter 13 JavaServer Pages Documents 515 The Example JSP Document 516 Creating a JSP Document 521 Declaring Tag Libraries 523 o se J2EETutorial book Page xvii Thursday June 3 2004 10 26 AM CONTENTS Including Directives in a JSP Document 525 Creating Static and Dynamic Content 527 Using the jsp root Element 530 Using the jsp output Element 531 Identifying the JSP Document to the Container 535 Chapter 14 JavaServer Pages Standard Tag Library 537 The Example JSP Pages 538 Using JSTL 541 Tag Collaboration 542 Core Tag Library 543 Variable Support Tags 543 Flow Control Tags 545 URL Tags 548 Miscellaneous Tags 549 XML Tag Library 550 Core Tags 551 Flow Control Tags 552 Transformation Tags 553 Internationalization Tag Library 554
12. Deploying the Coffee Break Server 1295 Building Packaging and Deploying the JavaServer Faces Technology Coffee Break Server 1297 Running the Coffee Break Client 1298 Removing the Coffee Break Application 1300 Chapter 36 The Duke s Bank Application 1301 Enterprise Beans 1302 Session Beans 1303 Entity Beans 1306 Helper Classes 1307 Database Tables 1308 Protecting the Enterprise Beans 1309 Application Client 1310 The Classes and Their Relationships 1311 BankAdmin Class 1312 EventHandle Class 1314 DataModel Class 1315 Web Client 1318 Design Strategies 1319 Client Components 1320 Request Processing 1323 Protecting the Web Client Resources 1325 Internationalization 1327 Building Packaging Deploying and Running the Application 1328 Setting Up the Servers 1328 Compiling the Duke s Bank Application Code 1330 Packaging and Deploying the Duke s Bank Application 1330 Reviewing JNDI Names 1335 18 se J2EETutorial book Page xxxii Thursday June 3 2004 10 26 AM xxxii CONTENTS Running the Clients 1338 Running the Application Client 1338 Running the Web Client 1339 Appendix A Java Encoding Schemes 1341 Further Information 1342 Appendix B XML and Related Specs Digesting the Alphabet SOUP cau cute pes anaana nanne 1343 Basic Standards 1344 SAX 1344 StAX 1345 DOM 1345 JDOM and dom4j 1345 DTD 1346 Namespaces 1347 XSL 1347 XSLT XPath 1347 Schema Standards 134
13. Enterprise Bean s Object Reference Using the Timer Service Creating Timers Canceling and Saving Timers Getting Timer Information Transactions and Timers The TimerSessionBean Example Building TimerSessionBean Handling Exceptions Chapter 26 Bean Managed Persistence Examples The SavingsAccountBean Example Entity Bean Class Home Interface Remote Interface Running the SavingsAccountBean Example Mapping Table Relationships for Bean Managed Persistence One to One Relationships One to Many Relationships Many to Many Relationships Primary Keys for Bean Managed Persistence The Primary Key Class Primary Keys in the Entity Bean Class Getting the Primary Key deploytool Tips for Entity Beans with Bean Managed Persistence o 879 880 880 880 881 882 884 884 885 886 888 889 889 890 891 892 893 893 894 894 895 896 901 903 904 914 916 917 919 919 922 930 933 934 935 936 937 4 se J2EETutorial book Page xxv Thursday June 3 2004 10 26 AM CONTENTS XXV Chapter 27 Container Managed Persistence Examples 939 Overview of the RosterApp Application 939 The PlayerBean Code 941 Entity Bean Class 941 Local Home Interface 946 Local Interface 947 Method Invocations in RosterApp 947 Creating a Player 948 Adding a Player to a Team 949 Removing a Player 950 Dropping a Player from a Team 951 Getting the Players of a Team 952 Getting a Copy of a Team s Players 953 Finding the P
14. HOW TO READ THIS TUTORIAL XXXIX Overview 1 a _ a Getting Started with Understanding Enterprise Web Applications 3 XML 2 Beans 23 29 ransactions 30 Resource Building Web Services with JAX RPC 8 EE Connections 31 Servlets 11 JAXP 4 7 j pt Security 32 JAXR 1 0 fh __ JMS 33 34 SAAJ 9 JSP 12 16 a Ee 4 Duke s Bank JSF 17 21 Case Study 36 pou Coffee Break 118n and Case Study 35 L10n 22 Figure 1 Roadmap to This Tutorial e The platform services chapters cover the system services used by all the J2EE component technologies e Transactions e Resource connections e Security e Jaya Message Service se J2EETutorial book Page xl Thursday June 3 2004 10 26 AM xl ABOUT THIS TUTORIAL After you have become familiar with some of the technology areas you are ready to tackle the case studies which tie together several of the technologies discussed in the tutorial The Coffee Break Application Chapter 35 describes an application that uses the Web application and Web services APIs The Duke s Bank Application Chapter 36 describes an application that employs Web appli cation technologies and enterprise beans Finally the appendixes contain auxiliary information helpful to the J2EE application developer along with a brief summary of the J2EE Connector architecture e Java Encoding Schemes Appendix A
15. Servlet Life Cycle Handling Servlet Life Cycle Events Handling Errors Sharing Information Using Scope Objects Controlling Concurrent Access to Shared Resources Accessing Databases Initializing a Servlet Writing Service Methods Getting Information from Requests Constructing Responses Filtering Requests and Responses Programming Filters Programming Customized Requests and Responses Specifying Filter Mappings Invoking Other Web Resources Including Other Resources in the Response Transferring Control to Another Web Component Accessing the Web Context Maintaining Client State Accessing a Session Associating Objects with a Session Session Management Session Tracking Finalizing a Servlet Tracking Service Requests Notifying Methods to Shut Down Creating Polite Long Running Methods Further Information o 429 430 433 433 434 435 436 440 441 441 443 444 444 445 446 447 448 449 451 454 454 456 458 460 461 462 463 464 464 465 466 466 467 468 469 470 470 XV 18 se J2EETutorial book Page xvi Thursday June 3 2004 10 26 AM xvi CONTENTS Chapter 12 JavaServer Pages Technology 471 What Is a JSP Page 471 Example 472 The Example JSP Pages 476 The Life Cycle of a JSP Page 482 Translation and Compilation 483 Execution 484 Creating Static Content 486 Response and Page Encoding 487 Creating Dynamic Content 487 Using Objects within JSP Pages 488 Expression Language 489
16. Setting the Locale 555 Messaging Tags 555 Formatting Tags 556 SQL Tag Library 556 query Tag Result Interface 559 Functions 561 Further Information 562 Chapter 15 Custom Tags in JSP Pages 563 What Is a Custom Tag 564 The Example JSP Pages 564 Types of Tags 568 Tags with Attributes 569 Tags with Bodies 572 Tags That Define Variables 572 Communication between Tags 573 Encapsulating Reusable Content Using Tag Files 573 Tag File Location 576 Tag File Directives 576 o xvii se J2EETutorial book Page xviii Thursday June 3 2004 10 26 AM xviii CONTENTS Evaluating Fragments Passed to Tag Files 584 Examples 585 Tag Library Descriptors 589 Top Level Tag Library Descriptor Elements 590 Declaring Tag Files 591 Declaring Tag Handlers 594 Declaring Tag Attributes for Tag Handlers 595 Declaring Tag Variables for Tag Handlers 596 Programming Simple Tag Handlers 598 Including Tag Handlers in Web Applications 599 How Is a Simple Tag Handler Invoked 599 Tag Handlers for Basic Tags 599 Tag Handlers for Tags with Attributes 600 Tag Handlers for Tags with Bodies 602 Tag Handlers for Tags That Define Variables 603 Cooperating Tags 606 Examples 608 Chapter 16 Scripting in JSP Pages 617 The Example JSP Pages 618 Using Scripting 619 Disabling Scripting 620 Declarations 620 Initializing and Finalizing a JSP Page 620 Scriptlets 621 Expressions 622 Programming Tags That Accep
17. asadmin and deploytool You will still have to provide the user name and password to log in to the Admin Console e Note the HTTP port at which the server is installed This tutorial assumes that you are accepting the default port of 8080 If 8080 is in use during installation and the installer chooses another port or if you decide to change it yourself you will need to update the common build properties file described in the next section and the configuration files for some of the tutorial examples to reflect the correct port In the Installation Options pane check the Add Bin Directory to PATH checkbox so that Application Server scripts asadmin asant deploytool and wscom pile override other installations Registry Server You need a registry server to run the examples discussed in Chapters 10 and 35 Directions for obtaining and setting up a registry server are provided in those chapters Building the Examples Most of the tutorial examples are distributed with a configuration file for asant a portable build tool contained in the Application Server This tool is an exten sion of the Ant tool developed by the Apache Software Foundation http ant apache org The asant utility contains additional tasks that invoke the Application Server administration utility asadmin Directions for building the examples are provided in each chapter Build properties and targets common to all the examples are specified in the files lt INST
18. bookcashier jsp page has the NameChanged listener implementation registered on it This listener saves the customer s name in the session scope when the bookcashier jsp page is submitted See Implementing Value Change Listeners page 748 for more information on how this listener works See Registering a ValueChangeListener on a Component page 711 to learn how the listener is registered on the tag Retrieving values from other implicit objects is done in a similar way to the example shown in this section Table 18 9 lists the implicit objects that a value attribute can refer to All of the implicit objects except for the scope objects are read only and therefore should not be used as a value for a UIInput component Table 18 9 Implicit Objects Implicit Object What It Is applicationScope A Map of the application scope attribute values keyed by attribute name A Map of the cookie values for the current request keyed by cookie name cookie facesContext The FacesContext instance for the current request Continues se J2EETutorial book Page 718 Thursday June 3 2004 10 26 AM 718 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Table 18 9 Implicit Objects Continued Implicit Object What It Is A Map of HTTP header values for the current request keyed by header name header A Map of String arrays containing all the header values for HTTP headerVal i ad headers in the current request keyed by header
19. listener implementation class This section explains how to register the NameChanged ValueChangeListener and a hypo thetical LocaleChange ActionListener implementation on components Imple menting Value Change Listeners page 748 explains how to implement NameChanged Implementing Action Listeners page 749 explains how to imple ment the hypothetical LocaleChange Registering a ValueChangeListener on a Component A page author can register a ValueChangeListener implementation on a UIInput component or a component represented by one of the subclasses of UIInput by nesting a valueChangeListener tag within the component s tag on the page Here is the tag corresponding to the name component from the book cashier jsp page lt h inputText id name size 50 value cashier name required true gt lt f valueChangeListener type listeners NameChanged gt lt h inputText gt The type attribute of the valueChangeListener tag specifies the fully qualified class name of the ValueChangeListener implementation After this component tag is processed and local values have been validated its corresponding component instance will queue the ValueChangeEvent asso ciated with the specified ValueChangeListener to the component Registering an ActionListener on a Component A page author can register an ActionListener implementation on a UICommand component by nesting an actionListener tag within the component s tag on o 711
20. mat of a time or the time part of a date string Applied only if type is time and pattern is not defined Valid values default short medium long and ful1 If no value is specified default is used timeZone String or TimeZone Time zone in which to interpret any time information in the date string String Specifies whether the string value will contain a date a time or both Valid values are date time or both If no value is specified date is used If you want to display the example date in Spanish you can use the parse Locale attribute lt h inputText value cashier shipDate gt lt f convertDateTime dateStyle fu11 locale Locale SPAIN timeStyle long type both gt lt h inputText gt This tag would display Sabado Feb 22 2003 se J2EETutorial book Page 709 Thursday June 3 2004 10 26 AM USING THE STANDARD CONVERTERS 709 Please refer to the Customizing Formats lesson of the Java Tutorial at http java sun com docs books tutorial i18n format simp1eDate Format htm1 for more information on how to format the output using the pat tern attribute of the convertDateTime tag Using NumberConverter You can convert a component s data to a java lang Number by nesting the con vertNumber tag inside the component tag The convertNumber tag has several attributes that allow you to specify the format and type of the data Table 18 6 lists the attributes Tabl
21. messages tag instead of the message tag all error messages will display The UlSelectOne Component A UISelectOne component allows the user to select one value from a set of values This component can be rendered as a list box a radio button or a menu This section explains the selectOneMenu tag The selectOneRadio and selectOneListbox tags are written in a similar way The selectOneListbox tag is similar to the selectOneMenu tag except that selectOneListbox defines a size attribute that determines how many of the items are displayed at once Using the selectOneMenu Tag The selectOneMenu tag represents a component that contains a list of items from which a user can choose one item The menu is also commonly known as a drop down list or a combo box The following code example shows the select OneMenu tag from the bookcashier jsp page of the Duke s Bookstore applica tion This tag allows the user to select a shipping method lt h selectOneMenu id shippingOption required true value cashier shippingOption gt lt f selectItem itemValue 2 itemLabel bundle QuickShip gt lt f selectItem itemValue 5 itemLabel bundle NormalShip gt o 699 18 se J2EETutorial book Page 700 Thursday June 3 2004 10 26 AM 700 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES lt f selectItem itemValue 7 itemLabel bundle SaverShip gt lt h selectOneMenu gt The value attribute of the selectO
22. name initParam A Map of the context initialization parameters for this Web application A Map of the request parameters for this request keyed by parameter param name A Map of String arrays containing all the parameter values for paramValues i request parameters in the current request keyed by parameter name requestScope A Map of the request attributes for this request keyed by attribute name sessionScope A Map of the session attributes for this request keyed by attribute name The root UIComponent in the current component tree stored in the view FacesRequest for this request Binding a Component Instance to a Bean Property A component instance can be bound to a bean property using a value binding expression with the binding attribute of the component s tag You usually bind a component instance rather than its value to a bean property if the bean must dynamically change the component s attributes Here are two tags from the bookcashier jsp page that bind components to bean properties lt h selectBooleanCheckbox id fanClub rendered false binding cashier specialOffer gt lt h outputLabel for fanClubLabel rendered false binding cashier specialOfferText gt o se J2EETutorial book Page 719 Thursday June 3 2004 10 26 AM REFERENCING A BACKING BEAN METHOD lt h outputText id fanClubLabel value bundle DukeFanClub gt lt h outputLabel
23. of the Update Quantities hyperlink is set to false If you click the Continue Shopping hyperlink none of the changes entered into the quantity input fields will be processed If you click the Update Quantities hyperlink the values in the quantity fields will be updated in the shopping cart The rendered Attribute A component tag uses a Boolean JavaServer Faces EL expression along with the rendered attribute to determine whether or not the component will be ren dered For example the check commandLink component on the bookcata log jsp page is not rendered if the cart contains no items lt h commandLink id check rendered 4 cart numberOfItems gt Q gt lt h outputText value bundle CartCheck gt lt h commandLink gt o 18 se J2EETutorial book Page 683 Thursday June 3 2004 10 26 AM USING THE HTML COMPONENT TAGS The style and styleClass Attributes The style and styleClass attributes allow you to specify Cascading Style Sheets CSS styles for the rendered output of your component tags The UIMes sage and UIMessages Components page 698 describes an example of using the style attribute to specify styles directly in the attribute A component tag can instead refer to a CSS stylesheet class The dataTable tag on the bookcata log jsp page of the Duke s Bookstore application references the style class 1ist background lt h dataTable id books styleClass list background value
24. s custom tag inside the component s tag To use a custom component you use the custom tag associated with the component As explained in Setting Up a Page page 676 you must ensure that the TLD that defines the custom tags is packaged in the application TLD files are stored in the WEB INF directory or subdirectory of the WAR file or in the META INF directory or subdirectory of a tag library packaged in a JAR se J2EETutorial book Page 724 Thursday June 3 2004 10 26 AM 724 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Next you include a taglib declaration so that the page has access to the tags All custom objects for the Duke s Bookstore application are defined in book store tld Here is the taglib declaration that you would include on your page so that you can use the tags from this TLD lt taglib uri WEB INF bookstore tld prefix bookstore gt When including the custom tag in the page you can consult the TLD to deter mine which attributes the tag supports and how they are used The next three sections describe how to use the custom converter validator and UI components included in the Duke s Bookstore application Using a Custom Converter To apply the data conversion performed by a custom converter to a particular component s value you must either set the converter attribute of the compo nent s tag to the Converter implementation s identifier or set the nested con verter tag s con
25. using different data structures including Array Map and Collection The data structure is composed of Selec tItem instances or SelectItemGroup instances o 0 se J2EETutorial book Page 701 Thursday June 3 2004 10 26 AM USING THE HTML CoMPONENT TAGS 701 yummy beans a into JR black garbanzo gross beans green string coffee baked T ALLIE Figure 18 2 An Example List Box Created Using SelectItemGroup Instances e You can concatenate different lists together into a single UISelectMany or UISelectOne component and group the lists within the component as shown in Figure 18 2 e You can dynamically generate values at runtime The advantages of using selectItem are as follows e The page author can define the items in the list from the page e You have less code to write in the bean for the selectItem properties For more information on writing component properties for the UISelectItems components see Writing Component Properties page 730 The rest of this sec tion shows you how to use the selectItems and selectItem tags Using the selectitems Tag Here is the selectManyCheckbox tag from the section The UISelectMany Com ponent page 697 lt h selectManyCheckbox id newsletters layout pageDirection value cashier newsletters gt lt f selectItems value newsletters gt lt h selectManyCheckbox gt 18 se J2EETutorial book Page 702 Th
26. 8 XML Schema 1349 RELAX NG 1349 SOX 1349 Schematron 1350 Linking and Presentation Standards 1350 XML Linking 1350 XHTML 1351 Knowledge Standards 1351 RDF 1351 RDF Schema 1352 XTM 1352 Standards That Build on XML 1352 Extended Document Standards 1333 e Commerce Standards 1353 Summary 1354 Appendix C HTTP Overview 1355 HTTP Requests 1356 HTTP Responses 1356 KZ Zs JQEETutorial book Page xxxiii Thursday June 3 2004 10 26 AM CONTENTS xxxiii Appendix D J2EE Connector Architecture 1357 About Resource Adapters 1357 Resource Adapter Contracts 1359 Management Contracts 1359 Outbound Contracts 1360 Inbound Contracts 1361 Common Client Interface 1362 Further Information 1363 GBIOSSOI A E E EEE EE EEE 1365 About the Authors 1403 Ra 1405 se J2EETutorial book Page xxxiv Thursday June 3 2004 10 26 AM 0 se J2EETutorial book Page xxxv Thursday June 3 2004 10 26 AM Foreword When the first edition of The J2EE Tutorial was released the Java 2 Plat form Enterprise Edition J2EE was the new kid on the block Modeled after its forerunner the Java 2 Platform Standard Edition J2SE the J2EE platform brought the benefits of Write Once Run Anywhere API compatibility to enterprise application servers Now at version 1 4 and with widespread conform ance in the application server marke
27. A component tag has a set of attributes for referencing backing bean methods that can perform certain functions for the component associated with the tag These attributes are summarized in Table 18 10 Only components that implement ActionSource can use the action and actionListener attributes Only UIInput components or components that extend UIInput can use the validator or valueChangeListener attributes 719 4 se J2EETutorial book Page 720 Thursday June 3 2004 10 26 AM 720 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Table 18 10 Component Tag Attributes that Reference Backing Bean Methods Refers to a backing bean method that performs navigation action processing for the component and returns a logical outcome String actionListener Refers to a backing bean method that handles ActionEvents Refers to a backing bean method that performs validation on the validator component s value Refers to a backing bean method that handles ValueChan valueChangeListener geEvents The component tag refers to a backing bean method using method binding expression as a value of one of the attributes The following four sections give examples of how to use the four different attributes Referencing a Method That Performs Navigation If your page includes a component such as a button or hyperlink that causes the application to navigate to another page when the component is activated the tag correspond
28. ALL gt j2eetutorial14 examples common build properties and o xli 18 se J2EETutorial book Page xlii Thursday June 3 2004 10 26 AM xlii amp ABOUT THIS TUTORIAL lt INSTALL gt j2eetutorial14 examples common targets xml Build proper ties and targets common to a particular technology are specified in the files lt INSTALL gt j2eetutorial14 examples tech common build properties and lt INSTALL gt j2eetutorial14 examples tech common targets xml To run the asant scripts you must set two common build properties as follows e Set the j2ee home property in the file lt INSTALL gt j2eetutorial14 examples common build properties to the location of your Applica tion Server installation The build process uses the j2ee home property to include the libraries in lt J2EE_HOME gt 1ib in the classpath All examples that run on the Application Server include the J2EE library archive lt J2EE_HOME gt 1ib j2ee jar in the build classpath Some examples use additional libraries in lt J2EE_HOME gt lib and lt J2EE_HOME gt 1ib endorsed the required libraries are enumerated in the individual tech nology chapters lt J2EE_HOME gt refers to the directory where you have installed the Application Server or the J2EE 1 4 SDK Note On Windows you must escape any backslashes in the j2ee home property with another backslash or use forward slashes as a path separator So if your Appli cation Server
29. HTML COMPONENT TAGS 693 instead of the commandLink tag if you always want the URL specified by the outputLink tag s value attribute to open and do not have to perform any processing when the user clicks on the link The Duke s Bookstore application does not utilize this tag but here is an example of it lt h outputLink value javadocs gt lt f verbatim gt Documentation for this demo lt f verbatim gt lt h outputLink gt As shown in this example the outputLink tag requires a nested verbatim tag which identifies the text the user clicks to get to the next page You can use the verbatim tag on its own when you want to simply output some text on the page Using the outputFormat Tag The outputFormat tag allows a page author to display concatenated messages as a MessageFormat pattern as described in the API documentation for java text MessageFormat see http java sun com j2se 1 4 2 docs api java text MessageFormat htm1 Here is an example of an outputFormat tag from the bookshowcart jsp page of the Duke s Bookstore application lt h outputFormat value 4 bundle CartItemCount gt lt f param value 4 cart numberOfItems gt lt h outputFormat gt The value attribute specifies the MessageFormat pattern The param tag speci fies the substitution parameters for the message In the example outputFormat tag the value for the parameter maps to the num ber of items in the shopping cart When the message is display
30. Image mapImage gt lt bookstore map gt The graphicImage tag associates an image world jpg with an image map that is referenced in the usemap attribute value 18 se J2EETutorial book Page 727 Thursday June 3 2004 10 26 AM USING CUSTOM OBJECTS 727 The custom map tag represents the custom component MapComponent specifies the image map and contains a set of custom area tags Each area tag represents a custom AreaComponent and specifies a region of the image map On the page the onmouseover and onmouseout attributes define the image that is displayed when the user performs the actions described by the attributes The page author defines what these images are The custom renderer also renders an onclick attribute In the rendered HTML page the onmouseover onmouseout and onclick attributes define which JavaScript code is executed when these events occur When the user moves the mouse over a region the onmouseover function associ ated with the region displays the map with that region highlighted When the user moves the mouse out of a region the onmouseout function redisplays the original image When the user clicks a region the onclick function sets the value of a hidden input tag to the ID of the selected area and submits the page When the custom renderer renders these attributes in HTML it also renders the JavaScript code The custom renderer also renders the entire onclick attribute rather than let the page
31. LLY INVALID Copyright 2004 Sun Microsystems Inc 4150 Network Circle Santa Clara California 95054 Etats Unis Tous droits r serv s Droits du gouvernement am ricain utlisateurs gouvernmentaux logiciel commercial Les utilisateurs gouvernmentaux sont soumis au contrat de licence standard de Sun Microsystems Inc ainsi qu aux dis positions en vigueur de la FAR Federal Acquisition Regulations et des suppl ments celles ci Cette distribution peut comprendre des composants d velopp s pardes tierces parties Sun Sun Microsystems le logo Sun Java JavaBeans JavaServer JavaServer Pages Enterprise Java Beans Java Naming and Directory Interface JavaMail JDBC EJB JSP J2EE J2SE Write Once Run Anywhere et le logo Java Coffee Cup sont des marques de fabrique ou des marques d pos es de Sun Microsystems Inc aux Etats Unis et dans d autres pays A moins qu autrement autoris le code de logiciel en tous les mat riaux techniques dans le pr sent articles y compris FAQs chantillons est fourni sous ce permis Les produits qui font l objet de ce manuel d entretien et les informations qu il contient sont r gis par la l gislation am ricaine en mati re de contr le des exportations et peuvent tre soumis au droit d autres pays dans le domaine des exportations et importations Les utilisations finales ou utilisateurs finaux pour des armes nucl aires des missiles des armes biologiques et ch
32. NT TAGS 685 In addition to the tag attributes listed in Using the HTML Component Tags page 680 the commandButton and commandLink tags can use these attributes e action which is either a logical outcome String or a method binding expression that points to a bean method that returns a logical outcome String In either case the logical outcome String is used by the default NavigationHandler instance to determine what page to access when the UICommand component is activated e actionListener which is a method binding expression that points to a bean method that processes an ActionEvent fired by the UICommand component See Referencing a Method That Performs Navigation page 720 for more infor mation on using the action attribute See Referencing a Method That Handles an ActionEvent page 721 for details on using the actionListener attribute Using the commandButton Tag The bookcashier jsp page of the Duke s Bookstore application includes a commandButton tag When a user clicks the button the data from the current page is processed and the next page is opened Here is the commandButton tag from bookcashier jsp lt h commandButton value bundle Submit action cashier submit gt Clicking the button will cause the submit method of CashierBean to be invoked because the action attribute references the submit method of the CashierBean backing bean The submit method performs some processing and returns a logi cal outcom
33. Page xxxvii Thursday June 3 2004 10 26 AM About This Tutorial Te J2EE Tutorial Second Edition is a guide to developing enterprise applications for the Java 2 Platform Enterprise Edition J2EE version 1 4 Here we cover all the things you need to know to make the best use of this tutorial Who Should Use This Tutorial This tutorial is intended for programmers who are interested in developing and deploying J2EE 1 4 applications on the Sun Java System Application Server Platform Edition 8 Prerequisites Before proceeding with this tutorial you should have a good knowledge of the Java programming language A good way to get to that point is to work through all the basic and some of the specialized trails in The Java Tutorial Mary Campione et al Addison Wesley 2000 In particular you should be familiar with relational database and security features described in the trails listed in Table 1 Table 1 Prerequisite Trails in The Java Tutorial JDBC http java sun com docs books tutorial jdbc Security http java sun com docs books tutorial security1 2 xxxvii De gt se J2EETutorial book Page xxxviii Thursday June 3 2004 10 26 AM xxxviii ABOUT THIS TUTORIAL How to Read This Tutorial The J2EE 1 4 platform is quite large and this tutorial reflects this However you don t have to digest everything in it at once This tutorial opens with three intro
34. age e Reference localized messages e Register converters validators and listeners on components e Bind components and their values to back end objects e Reference backing bean methods that perform navigation processing han dle events and perform validation This chapter also describes how to include custom objects created by application developers and component writers on a JSP page 671 se J2EETutorial book Page 672 Thursday June 3 2004 10 26 AM 672 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES The Example JavaServer Faces Application The JavaServer Faces technology chapters of this tutorial primarily use a rewrit ten version of the Duke s Bookstore example to illustrate the basic concepts of JavaServer Faces technology This version of the Duke s Bookstore example includes several JavaServer Faces technology features The JavaServer Faces implementation provides FacesServlet whose instances accept incoming requests and pass them to the implementation for processing Therefore the application does not need to include a serv let such as the Dispatcher servlet that processes request parameters and dispatches to application logic as do the other versions of Duke s Book store A custom image map component that allows you to select the locale for the application Navigation configured in a centralized application configuration resource file This eliminates the need to calculate URLs as other versio
35. at http java sun com j2ee javaserverfaces 1 0 docs tlddocs index htm1 for a complete list of the JavaServer Faces tags and their attributes Your application needs access to these TLDs in order for your pages to use them The Application Server includes these TLDs in jsf impl jar located in lt J2EE_HOME gt 1ib To use any of the JavaServer Faces tags you need to include these taglib direc tives at the top of each page containing the tags defined by these tag libraries lt taglib uri http java sun com jsf html prefix h gt lt taglib uri http java sun com jsf core prefix f gt The uri attribute value uniquely identifies the TLD The prefix attribute value is used to distinguish tags belonging to the tag library You can use other prefixes rather than the h or f prefixes However you must use the prefix you have chosen when including the tag in the page For example the form tag must be refer enced in the page via the h prefix because the preceding tag library directive uses the h prefix to distinguish the tags defined in html_basic tld lt h form gt A page containing JavaServer Faces tags is represented by a tree of components At the root of the tree is the UIViewRoot component The view tag represents 8 se J2EETutorial book Page 677 Thursday June 3 2004 10 26 AM SETTING UP A PAGE this component on the page Thus all component tags on the page must be enclosed in the view
36. author set it The custom renderer that renders the map tag also renders a hidden input com ponent that holds the current area The server side objects retrieve the value of the hidden input field and set the locale in the FacesContext according to which region was selected Chapter 20 describes the custom tags in more detail and also explains how to create the custom image map components renderers and tags se J2EETutorial book Page 728 Thursday June 3 2004 10 26 AM 0
37. bout developer features of the Application Server See the Sun Java System Application Server Platform Edition 8 Administra tion Guide at http docs sun com db doc 817 6088 for information about administering the Application Server Typographical Conventions Table 2 lists the typographical conventions used in this tutorial Table 2 Typographical Conventions Font Style italic Emphasis titles first occurrence of terms URLs code examples file names path names tool names monospace application names programming language keywords tag interface class method and field names properties italic monospace Variables in code file paths and URLs lt italic monospace gt User selected file path components se J2EETutorial book Page xliv Thursday June 3 2004 10 26 AM xliv ABOUT THIS TUTORIAL Menu selections indicated with the right arrow character for example First Second should be interpreted as select the First menu then choose Sec ond from the First submenu Acknowledgments The J2EE tutorial team would like to thank the J2EE specification leads Bill Shannon Pierre Delisle Mark Roth Yutaka Yoshida Farrukh Najmi Phil Good win Joseph Fialli Kate Stout and Ron Monzillo and the J2EE 1 4 SDK team members Vivek Nagar Tony Ng Qingging Ouyang Ken Saks Jean Francois Arcand Jan Luehe Ryan Lubke Kathy Walsh Binod P G Alejandro Murillo and Manveen Kaur The chap
38. c void setAge Integer age this age age 0 se J2EETutorial book Page 707 Thursday June 3 2004 10 26 AM USING THE STANDARD CONVERTERS 707 Alternatively if the component is not bound to a bean property you can use the converter attribute on the component tag lt h inputText value LoginBean Age converter javax faces convert IntegerConverter gt The data corresponding to this tag will be converted to a java lang Integer Notice that the Integer type is already a supported type of the NumberCon verter If you don t need to specify any formatting instructions using the convertNumber tag attributes and if one of the other converters will suffice you can simply reference that converter using the component tag s converter attribute Finally you can nest a converter tag within the component tag and refer to the converter s ID via the converter tag s converterId attribute If the tag is refer ring to a custom converter the value of converterID must match the ID in the application configuration resource file Here is an example lt h inputText value LoginBean Age gt lt f converter converterId Integer gt lt h inputText gt Using DateTimeConverter You can convert a component s data to a java util Date by nesting the con vertDateTime tag inside the component tag The convertDateTime tag has several attributes that allow you to specify the format and type of the data Table 18 5 list
39. cation Select Tools Deploy In the Connection Settings frame enter the user name and password you specified when you installed the Application Server Click OK A pop up dialog box will display the results of the deployment Click Close Open the URL http localhost 8080 bookstore6 in a browser o 675 e 18 se J2EETutorial book Page 676 Thursday June 3 2004 10 26 AM 676 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Setting Up a Page To use the JavaServer Faces UI components in your JSP page you need to give the page access to the two tag libraries the JavaServer Faces standard HTML ren der kit tag library and the JavaServer Faces core tag library The JavaServer Faces standard HTML render kit tag library defines tags that represent common HTML user interface components The JavaServer Faces core tag library defines tags that perform core actions and are independent of a particular render kit Using these tag libraries is similar to using any other custom tag library This chapter assumes that you are familiar with the basics of using custom tags in JSP pages see Using Custom Tags page 502 As is the case with any tag library each JavaServer Faces tag library must have a TLD that describes it The html_basic TLD describes the The JavaServer Faces standard HTML render kit tag library The jsf_core TLD describes the Java Server Faces core tag library Please refer to the TLD documentation
40. d in the tag See Configuring Navigation Rules page 805 for information on how to define navigation rules in the application configuration resource file Referencing a Method That Handles an ActionEvent If a component on your page generates an ActionEvent and if that event is han dled by a backing bean method you refer to the method by using the compo nent s actionListener attribute The chooselocale jsp page of the Duke s Bookstore application includes some components that generate action events One of them is the NAmerica component lt h commandLink id NAmerica action bookstore actionListener 1localeBean chooseLocaleFromLink gt The actionListener attribute of this component tag references the choose LocaleFromLink method using a method binding expression The chooseLocale FromLink method handles the event of a user clicking on the hyperlink rendered by this component The actionListener attribute can be used only with the tags of components that implement ActionSource These include UICommand components Writing a Method to Handle an ActionEvent page 757 describes how to imple ment a method that handles an action event 721 4 se J2EETutorial book Page 722 Thursday June 3 2004 10 26 AM 722 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Referencing a Method That Performs Validation If the input of one of the components on your page is validated by a backing bean method you ref
41. derer For example the inputText tag refers to a UIInput compo nent that is rendered with the Text renderer The UIInput component supports the following tag attributes in addition to the tag attributes described at the beginning of Using the HTML Component Tags page 680 The UIOutput component supports the first of the following tag attributes in addition to those listed in Using the HTML Component Tags page 680 e converter Identifies a converter that will be used to convert the compo nent s local data See Using the Standard Converters page 705 for more information on how to use this attribute o 18 se J2EETutorial book Page 691 Thursday June 3 2004 10 26 AM USING THE HTML CoMPONENT TAGS 691 Table 18 3 UIInput and UIOutput Renderers Renderer Function Allows a page author to include a Hidden inputhidden hidden variable in a page Accepts one line of text with no Secret inputSecret spaces and displays it as a set of UIInput me i asterisks as it is typed Text inputText Accepts a text string of one line TextArea inputTextarea Accepts multiple lines of text Displays a nested component as a Labe outputLabel label for a specified input field Displays an lt a href gt tag that outputLink links to another page without gen UIOutput i erating an ActionEvent OutputMessage outputFormat Displays a localized message Text outputText Displays a text string of
42. does not include this tag but here is an example of one lt h inputSecret redisplay false value LoginBean password gt In this example the redisplay attribute is set to false This will prevent the password from being displayed in a query string or in the source file of the resulting HTML page The UlPanel Component The UIPanel component is used as a layout container for its children When you use the renderers from the HTML render kit UIPanel is rendered as an HTML table This component differs from UIData in that UIData can dynamically add or delete rows to accommodate the underlying data source whereas UIPanel must have the number of rows predetermined Table 18 4 lists all the renderers and tags corresponding to the UIPanel component The panelGrid tag is used to represent an entire table The panelGroup tag is used to represent rows in a table Other UI component tags are used to represent individual cells in the rows 18 se J2EETutorial book Page 695 Thursday June 3 2004 10 26 AM USING THE HTML COMPONENT TAGS Table 18 4 UIPanel Renderers and Tags Tag Renderer Attributes Function columnClasses columns footerClass headerClass panel Class rowClasses panelGrid Displays a table Groups a set of components under one parent panelGroup The panelGrid tag has a set of attributes that specify CSS stylesheet classes columnClasses footerClass headerClass panelClass and rowClass
43. ductory chapters which you should read before proceeding to any specific technology area Chapter 1 covers the J2EE 1 4 platform architecture and APIs along with the Sun Java System Application Server Platform Edition 8 Chapters 2 and 3 cover XML basics and getting started with Web applications When you have digested the basics you can delve into one or more of the four main technology areas listed next Because there are dependencies between some of the chapters Figure 1 contains a roadmap for navigating through the tutorial e The Java XML chapters cover the technologies for developing applications that process XML documents and implement Web services components e The Java API for XML Processing JAXP e The Java API for XML based RPC JAX RPC e SOAP with Attachments API for Java SAAJ e The Java API for XML Registries JAXR e The Web tier technology chapters cover the components used in develop ing the presentation layer of a J2EE or stand alone Web application e Java Servlet e JavaServer Pages JSP e JavaServer Pages Standard Tag Library JSTL e JavaServer Faces e Web application internationalization and localization e The Enterprise JavaBeans EJB technology chapters cover the compo nents used in developing the business logic of a J2EE application e Session beans e Entity beans e Message driven beans e Enterprise JavaBeans Query Language 18 J2EETutorial book Page xxxix Thursday June 3 2004 10 26 AM
44. e This is passed to the default NavigationHandler which matches the outcome against a set of navigation rules defined in the application configu ration resource file The value attribute of the preceding example commandButton tag references the localized message for the button s label The bundle part of the expression refers to the ResourceBundle that contains a set of localized messages The Submit part of the expression is the key that corresponds to the message that is displayed on the button For more information on referencing localized messages see Using Localized Messages page 703 See Referencing a Method That Performs Navigation page 720 for information on how to use the action attribute 18 se J2EETutorial book Page 686 Thursday June 3 2004 10 26 AM 686 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Using the command Link Tag The commandLink tag represents an HTML hyperlink and is rendered as an HTML lt a gt element The commandLink tag is used to submit an action event to the application See Implementing Action Listeners page 749 for more infor mation on action events A commandLink tag must include a nested outputText tag which represents the text the user clicks to generate the event The following tag is from the choose locale jsp page from the Duke s Bookstore application lt h commandLink id NAmerica action bookstore actionListener 1localeBean chooseLocaleFromLink gt l
45. e 18 6 convertNumber Attributes Attribute Description ISO4217 currency code used only when formatting currencies Currency symbol applied only when formatting currencies Specifies whether formatted output contains grouping separators Specifies whether only the integer part of the value will be parsed Maximum number of digits formatted in the fractional part of the output Maximum number of digits formatted in the integer part of the output Minimum number of digits formatted in the fractional part of the output currencyCode String currencySymbol String groupingUsed boolean integerOnly boolean maxFractionDigits int maxIntegerDigits int minFractionDigits int minIntegerDigits int Minimum number of digits formatted in the integer part of the output Continues se J2EETutorial book Page 710 Thursday June 3 2004 10 26 AM 710 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Table 18 6 convertNumber Attributes Continued Attribute Type Description String or Locale Locale whose number styles are used to format or parse data Custom formatting pattern that determines how the number string is formatted and parsed pattern String Specifies whether the string value is parsed and format String ted as a number currency or percentage If not specified number is used The bookcashier jsp page of Duke s Bookstore uses a convertNumber tag to d
46. e 723 Thursday June 3 2004 10 26 AM USING CUSTOM OBJECTS 723 For illustration Writing a Method to Handle a Value Change Event page 758 describes how to implement this listener with a backing bean method instead of a listener implementation class To refer to this backing bean method the tag uses the valueChangeLi stener attribute lt h inputText id name size 50 value cashier name required true valueChangeListener cashier processValueChangeEvent gt lt h inputText gt The valueChangeListener attribute of this component tag references the pro cessValueChange method of CashierBean using a method binding expression The processValueChange method handles the event of a user entering his name in the input field rendered by this component The valueChangeListener attribute can be used only with the tags of UIInput components and components whose classes extend UIInput Writing a Method to Handle a Value Change Event page 758 describes how to implement a method that handles a ValueChangeEvent Using Custom Objects As a page author you might need to use custom converters validators or com ponents packaged with the application on your JSP pages A custom converter is applied to a component either by using the component tag s converter attribute or by nesting a converter tag inside the component s tag A custom validator is applied to a component by nesting either a validator tag or the validator
47. e Basic Structure Elements 283 Writing the Basic Program 287 o 4 se J2EETutorial book Page xiii Thursday June 3 2004 10 26 AM CONTENTS xiii Trimming the Whitespace 289 Processing the Remaining Structure Elements 291 Process Inline Content Elements 296 Printing the HTML 300 What Else Can XSLT Do 301 Transforming from the Command Line with Xalan 303 Concatenating Transformations with a Filter Chain 303 Writing the Program 303 Understanding How the Filter Chain Works 307 Testing the Program 308 Further Information 311 Chapter 8 Building Web Services with JAX RPC 313 Setting the Port 314 Creating a Simple Web Service and Client with JAX RPC 314 Coding the Service Endpoint Interface and Implementation Class 316 Building the Service 317 Packaging the Service 318 Specifying the Endpoint Address 320 Deploying the Service 320 Static Stub Client 321 Types Supported by JAX RPC 324 J2SE SDK Classes 324 Primitives 325 Arrays 325 Value Types 325 JavaBeans Components 326 Web Service Clients 326 Dynamic Proxy Client 326 Dynamic Invocation Interface Client 329 Application Client 333 More JAX RPC Clients 336 Web Services Interoperability and JAX RPC 337 Further Information 337 Chapter9 SOAP with Attachments API for Java 339 Overview of SAAJ 340 Messages 340 Connections 344 se J2EETutorial book Page xiv Thursday June 3 2004 10 26 AM xiv CONTENTS Tutorial 345 Creating and S
48. ectBoolean Component 697 The UlSelectMany Component 697 The UIMessage and UIMessages Components 698 The UlSelectOne Component 699 The UlSelectltem UISelectItems and UISelectItemGroup Components 700 Using Localized Messages 703 Referencing a ResourceBundle from a Page 704 Referencing a Localized Message 705 18 se J2EETutorial book Page xx Thursday June 3 2004 10 26 AM XX CONTENTS Using the Standard Converters Using DateTimeConverter Using NumberConverter Registering Listeners on Components Registering a ValueChangeListener on a Component Registering an ActionListener on a Component Using the Standard Validators Requiring a Value Using the LongRangeValidator Binding Component Values and Instances to External Data Sources Binding a Component Value to a Property Binding a Component Value to an Implicit Object Binding a Component Instance to a Bean Property Referencing a Backing Bean Method Referencing a Method That Performs Navigation Referencing a Method That Handles an ActionEvent Referencing a Method That Performs Validation Referencing a Method That Handles a ValueChangeEvent Using Custom Objects Using a Custom Converter Using a Custom Validator Using a Custom Component Chapter 19 Developing with JavaServer Faces Technology lt 2 cance eb he hehe eed Hs ce ee Writing Component Properties Writing Properties Bound to Component Values Writing Properties Bound to Component Instances Perform
49. ed in the page the number of items in the cart replaces the 0 in the message corresponding to the CartItemCount key in the bundle resource bundle Your shopping cart contains 0 choice 0 no items 1 one item 1 lt 0 items This message represents three possibilities e Your shopping cart contains no items e Your shopping cart contains one item e Your shopping cart contains 0 items 18 se J2EETutorial book Page 694 Thursday June 3 2004 10 26 AM 694 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES The value of the parameter replaces the 0 from the message in the sentence in the third bullet This is an example of a value binding enabled tag attribute accepting a complex JSP 2 0 EL expression An outputFormat tag can include more than one param tag for those messages that have more than one parameter that must be concatenated into the message If you have more than one parameter for one message make sure that you put the param tags in the proper order so that the data is inserted in the correct place in the message A page author can also hardcode the data to be substituted in the message by using a literal value with the value attribute on the param tag Using the inputSecret Tag The inputSecret tag renders an lt input type password gt HTML tag When the user types a string into this field a row of asterisks is displayed instead of the text the user types The Duke s Bookstore application
50. eld on the bookcashier jsp page of the Duke s Bookstore application lt h inputText id ccno size 19 required true gt lt bookstore formatValidator formatPatterns 9999999999999999 9999 9999 9999 9999 9999 9999 9999 9999 gt lt h inputText gt lt h message styleClass validationMessage for ccno gt This tag validates the input of the ccno field against the patterns defined by the page author in the formatPatterns attribute You can use the same custom validator for any similar component by simply nesting the custom validator tag within the component tag Creating a Custom Validator page 750 describes how to create the custom vali dator and its custom tag If the application developer who created the custom validator prefers to config ure the attributes in the Validator implementation rather than allow the page author to configure the attributes from the page the developer will not create a custom tag for use with the validator Instead the page author must follow these steps 1 Nest the validator tag inside the tag of the component whose data needs to be validated 2 Set the validator tag s validatorId attribute to the ID of the validator that is defined in the application configuration resource file Registering a Custom Validator page 803 explains how to define the validator in the application configuration resource file se J2EETutorial book Page 726 Thursday June 3 2004 10 26 AM 726
51. ementation will cre ate a DataModel wrapper around data of any of the other acceptable types See Writing Component Properties page 730 for more information on how to write properties for use with a UIData component The var attribute specifies a name that is used by the components within the dataTable tag as an alias to the data referenced in the value attribute of dataTable 4 se J2EETutorial book Page 689 Thursday June 3 2004 10 26 AM USING THE HTML COMPONENT TAGS In the dataTable tag from the bookshowcart jsp page the value attribute points to a List of books The var attribute points to a single book in that list As the UIData component iterates through the list each reference to item points to the current book in the list The UIData component also has the ability to display only a subset of the under lying data This is not shown in the preceding example To display a subset of the data you use the optional first and rows attributes The first attribute specifies the first row to be displayed The rows attribute specifies the number of rows starting with the first row to be displayed By default both first and rows are set to zero and this causes all the rows of the underlying data to display For example if you wanted to display records 2 through 10 of the underlying data you would set first to 2 and rows to 9 When you display a subset of the data in your pages you might want to consider includi
52. ending a Simple Message 346 Adding Content to the Header 355 Adding Content to the SOAPPart Object 356 Adding a Document to the SOAP Body 357 Manipulating Message Content Using SAAJ or DOM APIs 358 Adding Attachments 358 Adding Attributes 361 Using SOAP Faults 366 Code Examples 371 Request java 371 MyUddiPing java 373 HeaderExample java 380 DOMExample java and DOMSrcExample java 381 Attachments java 385 SOAPFaultTest java 387 Further Information 388 Chapter 10 Java API for XML Registries 389 Overview of JAXR 389 What Is a Registry 389 What Is JAXR 390 JAXR Architecture 391 Implementing a JAXR Client 393 Establishing a Connection 394 Querying a Registry 399 Managing Registry Data 404 Using Taxonomies in JAXR Clients 411 Running the Client Examples 417 Before You Compile the Examples 418 Compiling the Examples 420 Running the Examples 420 Using JAXR Clients in J2EE Applications 425 Coding the Application Client MyAppClient java 426 Coding the PubQuery Session Bean 427 Compiling the Source Files 427 Importing Certificates 428 Starting the Application Server 429 6 se J2EETutorial book Page xv Thursday June 3 2004 10 26 AM Chapter 11 CONTENTS Creating JAXR Resources Creating and Packaging the Application Deploying the Application Running the Application Client Further Information Java Servlet Technology What Is a Servlet The Example Servlets Troubleshooting
53. er Faces tags on the nested page In summary a typical JSP page that uses JavaServer Faces tags will look some what like this lt taglib uri http java sun com jsf html prefix h gt lt taglib uri http java sun com jsf core prefix f gt lt f view gt 677 18 se J2EETutorial book Page 678 Thursday June 3 2004 10 26 AM 678 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES lt h form gt other JavaServer Faces tags and core tags including one or more button or hyperlink components for submitting the form lt h form gt lt f view gt The sections Using the Core Tags page 678 and Using the HTML Component Tags page 680 describe how to use the core tags from the JavaServer Faces core tag library and the component tags from the JavaServer Faces standard HTML render kit tag library Using the Core Tags The tags included in the JavaServer Faces core tag library are used to perform core actions that are independent of a particular render kit These tags are listed in Table 18 1 Table 18 1 The jsf_core Tags Tag Categories Tags Functions Registers an action listener on a parent component actionListener Event handling tags Registers a value change listener on a valueChangeListener parent component Attribute configura Adds configurable attributes to a parent attribute tion tag component Registers an arbitrary converter on the parent component converter
54. er to the method from the component s tag using the vali dator attribute The Coffee Break application includes a method that performs validation of the email input component on the checkoutForm jsp page Here is the tag corre sponding to this component lt h inputText id email value checkoutFormBean email size 25 maxlength 125 validator checkoutFormBean validateEmail gt This tag references the validateEmail method described in Writing a Method to Perform Validation page 757 using a method binding expression The validator attribute can be used only with UIInput components or those components whose classes extend UIInput Writing a Method to Perform Validation page 757 describes how to implement a method that performs validation Referencing a Method That Handles a ValueChangeEvent If you want a component on your page to generate a ValueChangeEvent and you want that event to be handled by a backing bean method you refer to the method using the component s valueChangeListener attribute The name component on the bookcashier jsp page of the Duke s Bookstore application references a ValueChangeListener implementation that handles the event of a user entering a name in the name input field lt h inputText jd name size 50 value cashier name required true gt lt f valueChangeListener type listeners NameChanged gt lt h inputText gt o se J2EETutorial book Pag
55. erver Faces implemen tation checks whether the value of the component is nu11 or is an empty String If your component must have a non nu11 value or a String value at least one character in length you should add a required attribute to your component tag and set it to true If your tag does have a required attribute that is set to true and the value is nu11 or a zero length string no other validators registered on the tag are called If your tag does not have a required attribute set to true other validators registered on the tag are called but those validators must handle the possibility of a nu11 or zero length string Here is the name inputText tag lt h inputText id name size 50 value cashier name required true gt lt h inputText gt se J2EETutorial book Page 714 Thursday June 3 2004 10 26 AM 714 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Using the LongRangeValidator The Duke s Bookstore application uses a validateLongRange tag on the quan tity input field of the bookshowcart jsp page lt h inputText id quantity size 4 value item quantity gt lt f validateLongRange minimum 1 gt lt h inputText gt lt h message for quantity gt This tag requires that the user enter a number that is at least 1 The size attribute specifies that the number can have no more than four digits The validateLon gRange tag also has a maximum attribute with which you can set a maximum value o
56. es These stylesheet attributes are not required It also has a columns attribute The columns attribute is required if you want your table to have more than one col umn because the columns attribute tells the renderer how to group the data in the table If a headerClass is specified the panelGrid must have a header as its first child Similarly if a footerClass is specified the pane1Grid must have a footer as its last child The Duke s Bookstore application includes three panelGrid tags on the book cashier jsp page Here is a portion of one of them lt h panelGrid columns 3 headerClass 1ist header rowClasses list row even 1ist row odd styleClass list background title bundle Checkout gt lt f facet name header gt lt h outputText value bundle Checkout gt lt f facet gt lt h outputText value bundle Name gt lt h inputText id name size 50 value cashier name required true gt lt f valueChangeListener type listeners NameChanged gt lt h inputText gt lt h message styleClass validationMessage for name gt lt h outputText value bundle CCNumber gt 695 se J2EETutorial book Page 696 Thursday June 3 2004 10 26 AM 696 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES lt h inputText id ccno size 19 converter CreditCardConverter required true gt lt bookstore formatValidator formatPatterns 9999999999999999 9999 9999 9999 9999 9999
57. f the input Binding Component Values and Instances to External Data Sources As explained in Backing Bean Management page 656 a component tag can wire its component s data to a back end data object by doing one of the following e Binding its component s value to a bean property or other external data source e Binding its component s instance to a bean property A component tag s value attribute uses a value binding expression to bind a component s value to an external data source such as a bean property A compo nent tag s binding attribute uses a value binding expression to bind a compo nent instance to a bean property When referencing the property using the component tag s value attribute you need to use the proper syntax For example suppose a backing bean called MyBean has this int property int currentOption null int getCurrentOption void setCurrentOption int option The value attribute that references this property must have this value binding expression MyBean currentOption o se J2EETutorial book Page 715 Thursday June 3 2004 10 26 AM BINDING COMPONENT VALUES AND INSTANCES TO EXTERNAL DATA SOURCES 715 Table 18 8 Example Value Binding Expressions A Boolean cart numberOfItems gt 0 A property initialized from a Pate jnitParam quantity context init parameter A bean property CashierBean name Value in an array books 3 Value in a co
58. file o se J2EETutorial book Page 716 Thursday June 3 2004 10 26 AM 716 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES For example consider this managed bean configuration which configures the ImageArea bean corresponding to the North America part of the image map on the chooselocale jsp page of the Duke s Bookstore application lt managed bean gt lt managed bean name gt NA lt managed bean name gt lt managed bean class gt model ImageArea lt managed bean class gt lt managed bean scope gt application lt managed bean scope gt lt managed property gt lt property name gt shape lt property name gt lt value gt poly lt value gt lt managed property gt lt managed property gt lt property name gt alt lt property name gt lt value gt NAmerica lt value gt lt managed property gt lt managed bean gt This example configures a bean called NA which has several properties one of which is called shape Although the area tags on the chooselocale jsp page do not bind to an ImageArea property they bind to the bean itself to do this you refer to the property using a value binding expression from the value attribute of the com ponent s tag lt h outputText value NA shape gt Much of the time you will not include definitions for a managed bean s proper ties when configuring it You need to define a property and its value only when you want the property to be initiali
59. ge in which var matches the var attribute of the loadBundle tag and message matches the key of the message contained in the ResourceBundle referred to by the var attribute Here is an example from bookstore jsp lt h outputText value bundle Talk gt Notice that bundle matches the var attribute from the 1oadBundle tag and that Talk matches the key in the ResourceBundle Another example is the graphicImage tag from chooseLocale jsp lt h graphicImage id mapImage url template world jpg alt bundle ChooseLocale usemap worldMap gt The alt attribute is value binding enabled and this means that it can use value binding expressions In this case the alt attribute refers to localized text which will be included in the alternative text of the image rendered by this tag See Creating the Component Tag Handler page 772 and Enabling Value Binding of Component Properties page 783 for information on how to enable value bind ing on your custom component s attributes Using the Standard Converters The JavaServer Faces implementation provides a set of Converter implementa tions that you can use to convert component data For more information on the conceptual details of the conversion model see Conversion Model page 651 se J2EETutorial book Page 706 Thursday June 3 2004 10 26 AM 706 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES The standard Converter implementations located in the javax faces c
60. gt The selectBooleanCheckbox tag renders a checkbox and binds the fanClub UISelectBoolean component to the specialOffer property of CashierBean The outputLabel tag binds the component representing the checkbox s label to the specialOfferText property of CashierBean If the application s locale is English the outputLabel tag renders I d like to join the Duke Fan Club free with my purchase of over 100 The rendered attributes of both tags are set to false which prevents the check box and its label from being rendered If the customer orders more than 100 or 100 euros worth of books and clicks the Submit button the submit method of CashierBean sets both components rendered properties to true causing the checkbox and its label to be rendered These tags use component bindings rather than value bindings because the backing bean must dynamically set the values of the components rendered properties If the tags were to use value bindings instead of component bindings the back ing bean would not have direct access to the components and would therefore require additional code to access the components from the FacesContext to change the components rendered properties Writing Properties Bound to Component Instances page 739 explains how to write the bean properties bound to the example components and also discusses how the submit method sets the rendered properties of the components Referencing a Backing Bean Method
61. i rection which aligns the checkboxes horizontally The selectManyCheckbox tag must also contain a tag or set of tags representing the set of checkboxes To represent a set of items you use the selectItems tag To represent each item individually you use a selectItem tag for each item The UISelectItem UlSelectltems and UISelectltemGroup Components page 700 explains these two tags in more detail The UlMessage and UlMessages Components The UIMessage and UIMessages components are used to display error messages Here is an example message tag from the guessNumber application discussed in Steps in the Development Process page 635 lt h inputText id userNo value UserNumberBean userNumber lt f validateLongRange minimum maximum 10 gt lt h message se J2EETutorial book Page 699 Thursday June 3 2004 10 26 AM USING THE HTML COMPONENT TAGS style color red font family New Century Schoolbook serif font style oblique text decoration overline id errorsl for userNo gt The for attribute refers to the ID of the component that generated the error mes sage The message tag will display the error message wherever it appears on the page The style attribute allows you to specify the style of the text of the message In the example in this section the text will be red New Century Schoolbook serif font family and oblique style and a line will appear over the text If you use the
62. iis J2EETutorial book Page iii Thursday June 3 2004 10 26 AM The J2EE Tutorial Second Edition Stephanie Bodoff Eric Armstrong Jennifer Ball Debbie Bode Carson Ian Evans Dale Green Kim Haase Eric Jendrock vv Addison Wesley Boston San Francisco New York Toronto Montreal London Munich Paris Madrid Capetown Sydney Tokyo Singapore Mexico City o J2EETutorial book Page iv Thursday June 3 2004 10 26 AM Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book and Addison Wesley was aware of a trade mark claim the designations have been printed with initial capital letters or in all capitals The authors and publisher have taken care in the preparation of this book but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the infor mation or programs contained herein The publisher offers discounts on this book when ordered in quantity for bulk purchases and special sales For more information please contact U S Corporate and Government Sales 800 382 3419 corpsales pearsontechgroup com For sales outside of the U S please contact International Sales 317 581 3793 international
63. imiques ou du nucl aire maritime directement ou indirectement sont strictement interdites Les exportations ou r exportations vers des pays sous embargo des tats Unis ou vers des entit s figurant sur les listes d exclusion d exportation am ricaines y compris mais de mani re non exclusive la liste de personnes qui font objet d un ordre de ne pas participer d une fa on directe ou indirecte aux exportations des produits ou des services qui sont r gi par la l gislation am ricaine en mati re de contr le des exportations U S Commerce Depart ment s Table of Denial Orders et la liste de ressortissants sp cifiquement d sign s U S Treasury Department of Specially Designated Nationals and Blocked Persons sont rigoureusement interdites LA DOCUMENTATION EST FOURNIE EN L TAT ET TOUTES AUTRES CONDITIONS DE CLARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE A L APTITUDE A UNE UTILISATION PARTICULIERE OU A L ABSENCE DE CONTREFA ON o se J2EETutorial book Page vi Thursday June 3 2004 10 26 AM 0 se J2EETutorial book Page vii Thursday June 3 2004 10 26 AM Contents OIG WONG En ea a a a E a EA E at XXXV About This Tutorial XXXVII Chapter Overview
64. ing Localization Creating a Resource Bundle Localizing Dynamic Data Localizing Messages Creating a Custom Converter Implementing an Event Listener Implementing Value Change Listeners Implementing Action Listeners Creating a Custom Validator Implementing the Validator Interface Creating a Custom Tag Writing Backing Bean Methods Writing a Method to Handle Navigation o 705 707 709 710 711 711 712 713 714 714 715 717 718 719 720 721 722 722 723 724 725 726 730 730 739 741 741 741 742 744 747 748 749 750 751 753 755 755 8 se J2EETutorial book Page xxi Thursday June 3 2004 10 26 AM CONTENTS Writing a Method to Handle an ActionEvent Writing a Method to Perform Validation Writing a Method to Handle a Value Change Event Chapter 20 Creating Custom UI Components Chapter 21 Determining Whether You Need a Custom Component or Renderer When to Use a Custom Component When to Use a Custom Renderer Component Renderer and Tag Combinations Understanding the Image Map Example Why Use JavaServer Faces Technology to Implement an Image Map Understanding the Rendered HTML Understanding the JSP Page Configuring Model Data Summary of the Application Classes Steps for Creating a Custom Component Creating the Component Tag Handler Defining the Custom Component Tag in a Tag Library Descriptor Creating Custom Component Classes Performing Encoding Performing Decoding Enabli
65. ing the External Entity Summarizing Entities Choosing Your Parser Implementation Using the Validating Parser Configuring the Factory Validating with XML Schema Experimenting with Validation Errors Error Handling in the Validating Parser o 116 117 118 118 119 119 120 121 122 123 128 129 129 132 134 135 135 136 137 139 139 147 147 148 149 149 149 151 152 153 153 154 154 155 155 155 156 159 161 4 se J2EETutorial book Page xi Thursday June 3 2004 10 26 AM CONTENTS xi Parsing a Parameterized DTD 162 DTD Warnings 163 Handling Lexical Events 164 How the LexicalHandler Works 164 Working with a LexicalHandler 165 Using the DTDHandler and EntityResolver 171 The DTDHandler API 171 The EntityResolver API 172 Further Information 173 Chapter 6 Document Object Model 175 When to Use DOM 176 Documents Versus Data 176 Mixed Content Model 177 A Simpler Model 178 Increasing the Complexity 179 Choosing Your Model 181 Reading XML Data into a DOM 182 Creating the Program 182 Additional Information 186 Looking Ahead 188 Displaying a DOM Hierarchy 189 Convert DomEcho to a GUI App 189 Create Adapters to Display the DOM in a JTree 195 Finishing Up 204 Examining the Structure of a DOM 205 Displaying a Simple Tree 205 Displaying a More Complex Tree 207 Finishing Up 213 Constructing a User Friendly JTree from a DOM 213 Compressing the Tree View 213 Acting on Tree Selections
66. ing to this component must include an action attribute This attribute does one of the following e Specifies a logical outcome String that tells the application which page to access next e References a backing bean method that performs some processing and returns a logical outcome String The bookcashier jsp page of the Duke s Bookstore application has a command Button tag that refers to a backing bean method that calculates the shipping date If the customer has ordered more than 100 or 100 euros worth of books this method also sets the rendered properties of some of the components to true and returns null otherwise it returns receipt which causes the bookreceipt jsp page to display Here is the commandButton tag from the bookcashier jsp page se J2EETutorial book Page 721 Thursday June 3 2004 10 26 AM REFERENCING A BACKING BEAN METHOD lt h commandButton value bundle Submit action cashier submit gt The action attribute uses a method binding expression to refer to the submit method of CashierBean This method will process the event fired by the compo nent corresponding to this tag Writing a Method to Handle Navigation page 755 describes how to implement the submit method of CashierBean The application architect must configure a navigation rule that determines which page to access given the current page and the logical outcome which is either returned from the backing bean method or specifie
67. installation is C Sun AppServer you must set j2ee home as follows j2ee home C Sun AppServer or j2ee home C Sun AppServer e If you did not use port 8080 when you installed the Application Server set the value of the domain resources port property in lt INSTALL gt j2eetutorial14 examples common build properties to the correct port Tutorial Example Directory Structure To facilitate iterative development and keep application source separate from compiled files the source code for the tutorial examples is stored in the follow ing structure under each application directory 18 se J2EETutorial book Page xliii Thursday June 3 2004 10 26 AM TYPOGRAPHICAL CONVENTIONS xliii e build xml asant build file e src Java source of servlets and JavaBeans components tag libraries e web JSP pages and HTML pages tag files and images The asant build files build xm1 distributed with the examples contain targets to create a build subdirectory and to copy and compile files into that directory Further Information This tutorial includes the basic information that you need to deploy applications on and administer the Application Server For reference information on the tools distributed with the Application Server see the man pages at http docs sun com db doc 817 6092 See the Sun Java System Application Server Platform Edition 8 Developer s Guide at http docs sun com db doc 817 6087 for information a
68. isplay the total prices of the books in the shopping cart lt h outputText value cart total gt lt f convertNumber type currency lt h outputText gt Here is an example of a number this tag can display 934 This number can also be displayed using this tag lt h outputText id cartTotal value cart Total gt lt f convertNumber pattern gt lt h outputText gt Please refer to the Customizing Formats lesson of the Java Tutorial at http java sun com docs books tutorial i18n format decimalFormat html for more information on how to format the output using the pattern attribute of the convertNumber tag Registering Listeners on Components A page author can register a listener implementation class on a component by nesting either a valuechangeListener tag or an actionListener tag within the component s tag on the page o se J2EETutorial book Page 711 Thursday June 3 2004 10 26 AM REGISTERING LISTENERS ON COMPONENTS An application developer can instead implement these listeners as backing bean methods To reference these methods a page author uses the component tag s valueChangeListener and actionListener attributes as described in Refer encing a Method That Handles an ActionEvent page 721 and Referencing a Method That Handles a ValueChangeEvent page 722 The Duke s Bookstore application includes a value change listener implementa tion class but does not use an action
69. k box tag The selectManyListbox tag and selectManyMenu tag are written in a similar way A list box differs from a menu in that it displays a subset of items in a box whereas a menu displays only one item at a time until you select the menu The size attribute of the selectManyListbox tag determines the number of items displayed at one time The list box includes a scrollbar for scrolling through any remaining items in the list se J2EETutorial book Page 698 Thursday June 3 2004 10 26 AM 698 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Using the selectManyCheckbox Tag The selectManyCheckbox tag renders a set of checkboxes with each checkbox representing one value that can be selected Duke s Bookstore uses a select ManyCheckbox tag on the bookcashier jsp page to allow the user to subscribe to one or more newsletters lt h selectManyCheckbox id newsletters layout pageDirection value cashier newsletters gt lt f selectItems value news letters gt lt h selectManyCheckbox gt The value attribute of the selectManyCheckbox tag identifies the CashierBean backing bean property newsletters for the current set of newsletters This property holds the values of the currently selected items from the set of check boxes The layout attribute indicates how the set of checkboxes are arranged on the page Because layout is set to pageDi rection the checkboxes are arranged ver tically The default is 1ineD
70. layers by Position 955 Getting the Sports of a Player 956 Building and Running the RosterApp Example 958 Creating the Database Tables 958 Creating the Data Source 959 Capturing the Table Schema 959 Building the Enterprise Beans 960 Creating the Enterprise Application 960 Packaging the Enterprise Beans 961 Packaging the Enterprise Application Client 970 Deploying the Enterprise Application 971 Running the Client Application 971 A Guided Tour of the RosterApp Settings 972 RosterApp 972 RosterClient 974 RosterJAR 974 TeamJAR 975 Primary Keys for Container Managed Persistence 980 The Primary Key Class 982 Advanced CMP Topics The OrderApp Example 984 Structure of OrderApp 984 Bean Relationships in OrderApp 985 Primary Keys in OrderApp s Entity Beans 987 Entity Bean Mapped to More Than One Database Table 989 Finder and Selector Methods 990 Using Home Methods 990 18 Chapter 28 A Message Driven Bean Example Chapter 29 Enterprise JavaBeans Query Language se J2EETutorial book Page xxvi Thursday June 3 2004 10 26 AM CONTENTS Cascade Deletes in OrderApp BLOB and CLOB Database Types in OrderApp Building and Running the OrderApp Example deploytool Tips for Entity Beans with Container Managed Persistence Selecting the Persistent Fields and Abstract Schema Name Defining EJB QL Queries for Finder and Select Methods Defining Relationships Creating the Database Tables at Deploy Time in deploytool Example Application Over
71. llection books fiction Property of an object in an array of objects pooksielepeice In addition to binding a component s value to a bean property the value attribute can specify a literal value or can map the component s data to any prim itive such as int structure such as an array or collection such as a list independent of a JavaBeans component Table 18 8 lists some example value binding expressions that you can use with the value attribute The next two sections explain in more detail how to use the value attribute to bind a component s value to a bean property or other external data sources and how to use the binding attribute to bind a component instance to a bean property Binding a Component Value to a Property To bind a component s value to a bean property you specify the name of the bean and the property using the value attribute As explained in Backing Bean Management page 656 the value binding expression of the component tag s value attribute must match the corresponding managed bean declaration in the application configuration resource file This means that the name of the bean in the value binding expression must match the managed bean name element of the managed bean declaration up to the first in the expression Similarly the part of the value binding expression after the must match the name specified in the corresponding property name element in the application configuration resource
72. lt h column gt lt h column gt lt f facet name header gt lt h outputText value 4 bundle ItemTitle gt lt f facet gt lt h commandLink action showcart details gt lt h outputText value item item title gt lt h commandLink gt lt h column gt lt f facet name footer lt h panelGroup gt lt h outputText value 4 bundle Subtotal gt lt h outputText value cart total gt lt f convertNumber type currency gt lt h outputText gt lt h panelGroup gt lt f facet gt lt h dataTable gt Figure 18 1 shows a data grid that this dataTable tag can display Quantity Title Price El Web Servers for Fun and Profit OB 40 75 Remove ltem i Ine ae ob GI ci gt i Remove ten Java Intermediate Bytecodes 30 95 Benoveten Web Components for Web Developers 27 75 Benoveten From Oak to Java The Revolution of a Language 10 75 Renoveten Update Quantities Figure 18 1 Table on the bookshowcart jsp Page e se J2EETutorial book Page 688 Thursday June 3 2004 10 26 AM 688 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES The example dataTable tag displays the books in the shopping cart as well as the number of each book in the shopping cart the prices and a set of buttons which the user can click to remove books from the shopping cart The facet tag inside the first column tag renders a header fo
73. m Based Authentication sing Client Certificate Authentication sing Mutual Authentication qq m Gq sing Digest Authentication Configuring Authentication Example Using Form Based Authentication Installing and Configuring SSL Support Understanding Digital Certificates Configuring the SSL Connector XML and Web Services Security Example Basic Authentication with JAX RPC Example Client Certificate Authentication over HTTP SSL with JAX RPC EJB Tier Security Declaring Method Permissions Configuring IOR Security Using Programmatic Security in the EJB Tier Unauthenticated User Name Application Client Tier Security EIS Tier Security Container Managed Sign On Component Managed Sign On o 1080 1082 1083 1085 1086 4 se J2EETutorial book Page xxix Thursday June 3 2004 10 26 AM CONTENTS xxix Configuring Resource Adapter Security 1148 Propagating Security Identity 1149 Configuring a Component s Propagated Security Identity 1150 Configuring Client Authentication 1151 What Is Java Authorization Contract for Containers 1151 Further Information 1152 Chapter 33 The Java Message Service API 1153 Overview 1154 What Is Messaging 1154 What Is the JMS API 1154 When Can You Use the JMS API 1155 How Does the JMS API Work with the J2EE Platform 1156 Basic JMS API Concepts 1157 JMS API Architecture 1158 Messaging Domains 1159 Message Consumption 1161 The JMS API Programming Model
74. ment and applicable provisions of the FAR and its supplements This distribution may include materials developed by third parties Sun Sun Microsystems the Sun logo Java JavaBeans JavaServer JavaServer Pages Enterprise Java Beans Java Naming and Directory Interface JavaMail JDBC EJB JSP J2EE J2SE Write Once Run Anywhere and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems Inc in the U S and other countries Unless otherwise licensed software code in all technical materials herein including articles FAQs sam ples is provided under this License Products covered by and information contained in this service manual are controlled by U S Export Con trol laws and may be subject to the export or import laws in other countries Nuclear missile chemical biological weapons or nuclear maritime end uses or end users whether direct or indirect are strictly pro hibited Export or reexport to countries subject to U S embargo or to entities identified on U S export exclusion lists including but not limited to the denied persons and specially designated nationals lists is strictly prohibited DOCUMENTATION IS PROVIDED AS IS AND ALL EXPRESS OR IMPLIED CONDITIONS REPRESENTATIONS AND WARRANTIES INCLUDING ANY IMPLIED WARRANTY OF MER CHANTABILITY FITNESS FOR A PARTICULAR PURPOSE OR NON INFRINGEMENT ARE DISCLAIMED EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGA
75. mponent s local value is within a certain range The value must be a java lang String LengthValidator validateLength Checks whether the local value of a component is within a certain range LongRangeValidator validateLongRange The value must be any numeric type or String that can be con verted to a long se J2EETutorial book Page 713 Thursday June 3 2004 10 26 AM USING THE STANDARD VALIDATORS 713 All these validator classes implement the Validator interface Component writ ers and application developers can also implement this interface to define their own set of constraints for a component s value When using the standard Validator implementations you don t need to write any code to perform validation You simply nest the standard validator tag of your choice inside a tag that represents a component of type UIInput or a sub class of UIInput and provide the necessary constraints if the tag requires it Validation can be performed only on UIInput components or components whose classes extend UIInput because these components accept values that can be validated This section shows you how to use the standard Validator implementations See The UIMessage and UIMessages Components page 698 for information on how to display validation error messages on the page Requiring a Value The name inputText tag on the bookcashier jsp page has a required attribute which is set to true Because of this the JavaS
76. n Managed Transactions 1057 JDBC Transactions 1058 Deploying and Running the WarehouseBean Example 1059 Compiling the WarehouseBean Example 1059 Packaging the WarehouseBean Example 1059 JTA Transactions 1063 Deploying and Running the TellerBean Example 1064 Compiling the TellerBean Example 1064 Packaging the TellerBean Example 1065 Returning without Committing 1068 Methods Not Allowed in Bean Managed Transactions 1068 Summary of Transaction Options for Enterprise Beans 1069 Transaction Timeouts 1070 Isolation Levels 1070 Updating Multiple Databases 1071 Transactions in Web Components 1073 Chapter 31 Resource Connections 1075 JNDI Naming 1075 DataSource Objects and Connection Pools 1077 Database Connections 1078 Coding a Database Connection 1078 Specifying a Resource Reference 1079 Creating a Data Source 1079 gt 18 Chapter 32 Security se J2EETutorial book Page xxviii Thursday June 3 2004 10 26 AM CONTENTS Mail Session Connections Running the ConfirmerBean Example URL Connections Running the HTMLReaderBean Example Further Information Overview Realms Users Groups and Roles Managing Users Setting Up Security Roles Mapping Roles to Users and Groups Web Tier Security Protecting Web Resources Setting Security Requirements Using deploytool Specifying a Secure Connection Using Programmatic Security in the Web Tier Understanding Login Authentication sing HTTP Basic Authentication sing For
77. n com docs books tutorial i18n index htm After the application developer has produced a ResourceBundie the application architect puts it in the same directory as the application classes Much of the data for the Duke s Bookstore application is stored in a ResourceBundle called BookstoreMessages Referencing a ResourceBundle from a Page For a page with JavaServer Faces tags to use the localized messages contained in a ResourceBundle the page must reference the ResourceBundle using a load Bundle tag The ToadBundle tag from bookstore jsp is lt f loadBundle var bundle basename messages BookstoreMessages gt The basename attribute value refers to the ResourceBundle located in the mes sages package of the bookstore application Make sure that the basename attribute specifies the fully qualified class name of the file 18 se J2EETutorial book Page 705 Thursday June 3 2004 10 26 AM USING THE STANDARD CONVERTERS 705 The var attribute is an alias to the ResourceBundle This alias can be used by other tags in the page in order to access the localized messages Referencing a Localized Message To reference a localized message from a ResourceBundle you use a value bind ing expression from an attribute of the component tag that will display the local ized data You can reference the message from any component tag attribute that is value binding enabled The value binding expression has the notation var messa
78. nd steady ing influence se J2EETutorial book Page xlv Thursday June 3 2004 10 26 AM FEEDBACK xlv We also thank Duarte Design Inc and Zana Vartanian for developing the illus trations in record time Thanks are also due to our copy editor Betsy Hardinger for helping this multi author project achieve a common style Finally we would like to express our profound appreciation to Ann Sellers Elizabeth Ryan and the production team at Addison Wesley for graciously see ing our large complicated manuscript to publication Feedback To send comments broken link reports errors suggestions and questions about this tutorial to the tutorial team please use the feedback form at http java sun com j2ee 1 4 docs tutorial information sendusmail html se J2EETutorial book Page xlvi Thursday June 3 2004 10 26 AM 0 a J2EETutorial book Page 671 Thursday June 3 2004 10 26 AM 18 Using JavaServer Faces Technology in JSP Pages Tue page author s responsibility is to design the pages of a JavaServer Faces application This includes laying out the components on the page and wiring them to backing beans validators converters and other back end objects associ ated with the page This chapter uses the Duke s Bookstore application and the Coffee Break application see Chapter 35 to describe how page authors use the JavaServer Faces tags to e Layout standard UI components on a p
79. neMenu tag maps to the property that holds the currently selected item s value Like the selectOneRadio tag the selectOneMenu tag must contain either a selectItems tag or a set of selectItem tags for representing the items in the list The next section explains these two tags The UlSelectltem UlSelectltems and UlSelectitemGroup Components UISelectItem and UISelectItems represent components that can be nested inside a UISelectOne or a UISelectMany component UISelectItem is associ ated with a SelectItem instance which contains the value label and descrip tion of a single item in the UISelectOne or UISelectMany component The UISelectItems instance represents either of the following e A set of SelectItem instances containing the values labels and descrip tions of the entire list of items e A set of SelectItemGroup instances each of which represents a set of SelectItem instances Figure 18 2 shows an example of a list box constructed with a SelectItems component representing two SelectItemGroup instances each of which repre sents two categories of beans Each category is an array of SelectItem instances The selectItem tag represents a UISelectItem component The selectItems tag represents a UISelectItems component You can use either a set of select Item tags or a single selectItems tag within your selectOne or selectMany tag The advantages of using the selectItems tag are as follows e You can represent the items
80. ng Value Binding of Component Properties Saving and Restoring State Delegating Rendering to a Renderer Creating the Renderer Class Identifying the Renderer Type Handling Events for Custom Components Configuring JavaServer Faces Applications Application Configuration Resource File Configuring Beans Using the managed bean Element Initializing Properties using the managed property Element Initializing Maps and Lists Registering Messages Registering a Custom Validator Registering a Custom Converter Configuring Navigation Rules o 757 757 758 762 762 763 764 765 765 766 767 769 770 771 772 777 778 780 783 783 785 786 786 788 788 791 792 793 793 795 801 802 803 804 805 xxi 18 Chapter 22 Chapter 23 Enterprise Beans se J2EETutorial book Page xxii Thursday June 3 2004 10 26 AM CONTENTS Registering a Custom Renderer with a Render Kit Registering a Custom Component Basic Requirements of a JavaServer Faces Application Configuring an Application Using deploytool Including the Required JAR Files Including the Classes Pages and Other Resources Internationalizing and Localizing Web Applications Java Platform Localization Classes Providing Localized Messages and Labels Establishing the Locale Setting the Resource Bundle Retrieving Localized Messages Date and Number Formatting Character Sets and Encodings Character Sets Charac
81. ng a link or button that causes subsequent rows to display when clicked The dataTable tag also has a set of optional attributes for adding styles to the table e columnClasses Defines styles for all the columns e footerClass Defines styles for the footer e headerClass Defines styles for the header e rowClasses Defines styles for the rows e styleClass Defines styles for the entire table Each of these attributes can specify more than one style If columnClasses or rowClasses specifies more than one style the styles are applied to the columns or rows in the order that the styles are listed in the attribute For example if col umnClasses specifies styles 1ist column center and 1ist column right and if there are two columns in the table the first column will have style list column center and the second column will have style 1ist column right If the style attribute specifies more styles than there are columns or rows the remaining styles will be assigned to columns or rows starting from the first col umn or row Similarly if the style attribute specifies fewer styles than there are columns or rows the remaining columns or rows will be assigned styles starting from the first style 689 18 se J2EETutorial book Page 690 Thursday June 3 2004 10 26 AM 690 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES The UlGraphic Component The UIGraphic component displays an image The Duke s Bookstore appli cation use
82. ns of the Duke s Bookstore application must do Backing beans associated with the pages These beans hold the component data and perform other processing associated with the components This processing includes handling the event generated when a user clicks a but ton or hyperlink Tables that display the books from the database and the shopping cart are rendered with the dataTable tag which is used to dynamically render data in a table The dataTable tag on bookshowcart jsp also includes input components A custom validator and a custom converter are registered on the credit card field of the bookcashier jsp page A value change listener is registered on the Name field of bookcash ier jsp This listener saves the name in a parameter so that book receipt jsp can access it This version of Duke s Bookstore includes the same pages listed in Table 12 1 It also includes the chooselocale jsp page which displays the custom image map that allows you to select the locale of the application This page is displayed first and advances directly to the bookstore jsp page after the locale is selected 4 se J2EETutorial book Page 673 Thursday June 3 2004 10 26 AM THE EXAMPLE JAVASERVER FACES APPLICATION The packages of the Duke s Bookstore application are backing Includes the backing bean classes components Includes the custom UI component classes converters Includes the custom converter class listeners Incl
83. nt s immediate value determines what happens when the command com ponent is activated Assume that you have a page with a button and a field for entering the quantity of a book in a shopping cart If both the button s and the field s immediate attributes are set to true the new value of the field will be available for any pro cessing associated with the event that is generated when the button is clicked The event associated with the button and the event validation and conversion associated with the field are all handled during the apply request values phase If the button s immediate attribute is set to true but the field s immediate attribute is set to false the event associated with the button is processed with out updating the field s local value to the model layer This is because any events conversion or validation associated with the field occurs during its usual phases of the life cycle which come after the apply request values phase The bookshowcart jsp page of the Duke s Bookstore application has examples of components using the immediate attribute to control which component s data is updated when certain buttons are clicked The quantity field for each book has its immediate attribute set to false The quantity fields are generated by the UIData component See The UIData Component page 686 for more infor mation The immediate attribute of the Continue Shopping hyperlink is set to true The immediate attribute
84. odulo 3 So if a component is the fifth one in the list of components that component will be in the 5 modulo 3 column or column 2 4 se J2EETutorial book Page 697 Thursday June 3 2004 10 26 AM USING THE HTML COMPONENT TAGS 697 The UlSelectBoolean Component The UISelectBoolean class defines components that have a boolean value The selectBooleanCheckbox tag is the only tag that JavaServer Faces technology provides for representing boolean state The Duke s Bookstore application includes a selectBooleanCheckbox tag on the bookcashier jsp page lt h selectBooleanCheckbox id fanClub rendered false binding cashier specialOffer gt lt h outputLabel for fanClubLabel rendered false binding cashier specialOfferText gt lt h outputText id fanClubLabel value bundle DukeFanClub gt lt h outputLabel gt This example tag displays a checkbox to allow users to indicate whether they want to join the Duke Fan Club The label for the checkbox is rendered by the outputLabel tag The actual text is represented by the nested outputText tag Binding a Component Instance to a Bean Property page 718 discusses this example in more detail The UlSelectMany Component The UISelectMany class defines a component that allows the user to select zero or more values from a set of values This component can be rendered as a set of checkboxes a list box or a menu This section explains the selectManyChec
85. one line e validator Identifies a method binding expression pointing to a backing bean method that performs validation on the component s data See Refer encing a Method That Performs Validation page 722 for an example of using the validator tag e valueChangeListener Identifies a method binding expression pointing to a backing bean method that handles the event of entering a value in this component See Referencing a Method That Handles a ValueChangeEvent page 722 for an example of using valueChangeListener The rest of this section explains how to use selected tags listed in Table 18 3 The other tags are written in a similar way Using the outputText and inputText Tags The Text renderer can render both UIInput and UIOutput components The inputText tag displays and accepts a single line string The outputText tag displays a single line string This section shows you how to use the inputText tag The outputText tag is written in a similar way o se J2EETutorial book Page 692 Thursday June 3 2004 10 26 AM 692 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Here is an example of an inputText tag from the bookcashier jsp page lt h inputText id name size 50 value cashier name required true gt lt f valueChangeListener type listeners NameChanged gt lt h inputText gt The value attribute refers to the name property of CashierBean This property holds the data for the name comp
86. onent After the user submits the form the value of the name property in CashierBean will be set to the text entered in the field corresponding to this tag The required attribute causes the page to reload with errors displayed if the user does not enter a value in the name text field See Requiring a Value page 713 for more information on requiring input for a component Using the outputLabel Tag The outputLabel tag is used to attach a label to a specified input field for acces sibility purposes The bookcashier jsp page uses an outputLabel tag to ren der the label of a checkbox lt h selectBooleanCheckbox id fanClub rendered false binding cashier specialOffer gt lt h outputLabel for fanClubLabel rendered false binding cashier specialOfferText gt lt h outputText id fanClubLabel value bundle DukeFanClub gt lt h outputLabel gt The for attribute of the outputLabel tag maps to the id of the input field to which the label is attached The outputText tag nested inside the outputLabel tag represents the actual label component The value attribute on the outputText tag indicates the text that is displayed next to the input field Using the outputLink Tag The outputLink tag is used to render a hyperlink that when clicked loads another page but does not generate an action event You should use this tag 18 se J2EETutorial book Page 693 Thursday June 3 2004 10 26 AM USING THE
87. onvert package are as follows e BigDecimalConverter e BigIntegerConverter e BooleanConverter e ByteConverter e CharacterConverter e DateTimeConverter e DoubleConverter e FloatConverter e IntegerConverter e LongConverter e NumberConverter e ShortConverter Two of these standard converters DateTimeConverter and NumberConverter have their own tags which allow you to configure the format of the component data by configuring the tag attributes Using DateTimeConverter page 707 discusses using DateTimeConverter Using NumberConverter page 709 dis cusses using NumberConverter You can use the other standard converters in one of three ways e You can make sure that the component that uses the converter has its value bound to a backing bean property of the same type as the converter e You can refer to the converter by class or by its ID using the component tag s converter attribute The ID is defined in the application configura tion resource file see Application Configuration Resource File page 792 e You can refer to the converter by its ID using the converterId attribute of the converter tag The latter two will convert the component s local value The first method will convert the model value of the component For example if you want a compo nent s data to be converted to an Integer you can bind the component to a prop erty similar to this Integer age Q public Integer getAgeQ return age publi
88. ource and binds the component s value to it e binding Identifies a bean property and binds the component instance to it All of the UI component tag attributes except id and var are value binding enabled which means that they accept JavaServer Faces EL expressions These expressions allow you to use mixed literals and JSP 2 0 expression language syntax and operators See Expression Language page 489 for more information about the JSP 2 0 expression language The id Attribute The id attribute is not required for a component tag except in these situations e Another component or a server side class must refer to the component e The component tag is impacted by a JSTL conditional or iterator tag for more information see Flow Control Tags page 545 If you don t include an id attribute the JavaServer Faces implementation auto matically generates a component ID The immediate Attribute UIInput components and command components those that implement Action Source such as buttons and hyperlinks can set the immediate attribute to true to force events validations and conversions to be processed during the apply request values phase of the life cycle Page authors need to carefully consider o 681 18 se J2EETutorial book Page 682 Thursday June 3 2004 10 26 AM 682 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES how the combination of an input component s immediate value and a command compone
89. pearsontechgroup com Visit Addison Wesley on the Web www awprofessional com Library of Congress Cataloging in Publication Data The J2EE tutorial Stephanie Bodoff et al 2nd ed p cm Includes bibliographical references and index ISBN 0 321 24575 X pbk alk paper 1 Java Computer program language 2 Business Data processing I Bodoff Stephanie QA76 73 J38J32 2004 005 2 762 dc22 2004005648 Copyright 2004 by Sun Microsystems All rights reserved No part of this publication may be reproduced stored in a retrieval system or trans mitted in any form or by any means electronic mechanical photocopying recording or otherwise without the prior consent of the publisher Printed in the United States of America Published simulta neously in Canada For information on obtaining permission for use of material from this work please submit a written request to Pearson Education Inc Rights and Contracts Department 75 Arlington Street Suite 300 Boston MA 02116 Fax 617 848 7047 ISBN 0 321 24575 X Text printed on recycled paper 123456789 10 CRW 0807060504 First printing June 2004 J2EETutorial book Page v Thursday June 3 2004 10 26 AM Copyright 2004 Sun Microsystems Inc 4150 Network Circle Santa Clara California 95054 U S A All rights reserved U S Government Rights Commercial software Government users are subject to the Sun Microsystems Inc standard license agree
90. r lt INSTALL gt j2eetutorial14 exam ples web bookstore6 war c In the WAR Name field enter bookstore6 o 673 18 se J2EETutorial book Page 674 Thursday June 3 2004 10 26 AM 674 10 ee sB py oO p USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES In the Context Root field enter bookstore6 Click Edit Contents In the Edit Contents dialog box navigate to lt INSTALL gt j2ee tutorial14 examples web bookstore6 bui 1d Select everything in the build directory and click Add In the Contents tree drag the resources package to the WEB INF classes directory In the Contents tree drag faces config xml to the WEB INF direc tory In the Edit Contents dialog box navigate to lt INSTALL gt j2eetutorial14 examples web bookstore dist Select book store jar and click Add In the Edit Contents dialog box navigate to lt J2EE_HOME gt lib and select the jsf api jar Click Add and then Click OK Click Next Select the Servlet radio button Click Next Select javax faces webapp FacesServlet from the Servlet Class combo box In the Startup Load Sequence Position combo box enter 1 Click Finish Provide a mapping for the FacesServlet Web component a b C Select the FacesServlet Web component that is contained in the bookstore6 Web application from the tree Select the Aliases tab Click Add and enter faces in the Aliases field Specify where state is saved
91. r that column The other column tags also contain facet tags Facets can have only one child and so a panelGroup tag is needed if you want to group more than one component within a facet Because the facet tag representing the footer includes more than one tag the panelGroup is needed to group those tags A facet tag is usually used to represent headers and footers In general a facet is used to represent a component that is independent of the parent child relation ship of the page s component tree In the case of a data grid header and footer data is not repeated like the other rows in the table and therefore the elements representing headers and footers are not updated as are the other components in the tree This example is a classic use case for a UIData component because the number of books might not be known to the application developer or the page author at the time the application is developed The UIData component can dynamically adjust the number of rows of the table to accommodate the underlying data The value attribute of a dataTable tag references the data to be included in the table This data can take the form of e A list of beans e An array of beans e A single bean e A javax faces model DataModel e A java sql ResultSet e A javax servlet jsp jstl sql ResultSet e A javax sql RowSet All data sources for UIData components have a DataModel wrapper Unless you explicitly construct a DataModel the JavaServer Faces impl
92. rprise Bean 854 Compiling the Source Files 856 Packaging the Enterprise Bean 857 Creating the Application Client 858 Coding the Application Client 859 Compiling the Application Client 861 Packaging the Application Client 861 Specifying the Application Client s Enterprise Bean Reference 862 Creating the Web Client 863 Coding the Web Client 863 Compiling the Web Client 865 Packaging the Web Client 865 Specifying the Web Client s Enterprise Bean Reference 866 Mapping the Enterprise Bean References 866 Specifying the Web Client s Context Root 868 Deploying the J2EE Application 868 Running the Application Client 869 Running the Web Client 869 Modifying the J2EE Application 870 Modifying a Class File 870 Adding a File 871 Modifying a Deployment Setting 872 Chapter 25 Session Bean Examples 873 The CartBean Example 873 Session Bean Class 874 Home Interface 878 18 se J2EETutorial book Page xxiv Thursday June 3 2004 10 26 AM xxiv CONTENTS Remote Interface Helper Classes Building the CartBean Example Creating the Application Packaging the Enterprise Bean Packaging the Application Client A Web Service Example HelloServiceBean Web Service Endpoint Interface Stateless Session Bean Implementation Class Building HelloServiceBean Building the Web Service Client Running the Web Service Client Other Enterprise Bean Features Accessing Environment Entries Comparing Enterprise Beans Passing an
93. rver Faces These new o XXXV 18 se J2EETutorial book Page xxxvi Thursday June 3 2004 10 26 AM XXXVi FOREWORD technologies are available in the Sun Java System Application Server They will soon be featured in new developer tools and are strong candidates for inclusion in the next version of the J2EE platform Readers conversant with the core J2EE platform enterprise bean technology will notice major upgrades with the addition of the previously mentioned Web ser vice endpoints as well as a timer service and enhancements to EJB QL and message driven beans With all of these new features I believe that you will find it well worth your time and energy to take on the J2EE 1 4 platform You can increase the scope of the J2EE applications you develop and your applications will run on the widest pos sible range of application server products To help you to learn all about the J2EE 1 4 platform The J2EE Tutorial Sec ond Edition follows the familiar Java Series tutorial model of concise descrip tions of the essential features of each technology with code examples that you can deploy and run on the Sun Java System Application Server Read this tutorial and you will become part of the next wave of J2EE application developers Jeff Jackson Vice President J2EE Platform and Application Servers Sun Microsystems Santa Clara CA Thursday June 3 2004 18 SW AIS J2EETutorial book
94. s 28 Chapter 2 Understanding XML 31 Introduction to XML 31 What Is XML 31 Why Is XML Important 36 How Can You Use XML 38 Generating XML Data 41 Writing a Simple XML File 41 Defining the Root Element 42 Writing Processing Instructions 46 Introducing an Error 48 Substituting and Inserting Text 49 Creating a Document Type Definition 52 Documents and Data 57 Defining Attributes and Entities in the DTD 57 Referencing Binary Entities 64 Defining Parameter Entities and Conditional Sections 66 Resolving a Naming Conflict 70 Using Namespaces 71 gt 18 se J2EETutorial book Page ix Thursday June 3 2004 10 26 AM CONTENTS ix Designing an XML Data Structure 74 Saving Yourself Some Work 74 Attributes and Elements 75 Normalizing Data 77 Normalizing DTDs 78 Summary 79 Chapter 3 Getting Started with Web Applications 81 Web Application Life Cycle 84 Web Modules 86 Packaging Web Modules 88 Deploying Web Modules 89 Listing Deployed Web Modules 92 Updating Web Modules 92 Undeploying Web Modules 95 Configuring Web Applications 95 Mapping URLs to Web Components 96 Declaring Welcome Files 97 Setting Initialization Parameters 98 Mapping Errors to Error Screens 99 Declaring Resource References 99 Duke s Bookstore Examples 100 Accessing Databases from Web Applications 100 Populating the Example Database 101 Creating a Data Source in the Application Server 102 Specifying a Web Applica
95. s a graphicImage tag to display the map image on the chooselocale jsp page lt h graphicImage id mapImage url template world jpg alt bundle chooseLocale usemap worldMap gt The ur attribute specifies the path to the image It also corresponds to the local value of the UIGraphic component so that the URL can be retrieved possibly from a backing bean The URL of the example tag begins with a which adds the relative context path of the Web application to the beginning of the path to the image The alt attribute specifies the alternative text displayed when the user mouses over the image In this example the alt attribute refers to a localized message See Performing Localization page 741 for details on how to localize your Java Server Faces application The usemap attribute refers to the image map defined by the custom component MapComponent which is on the same page See Chapter 20 for more information on the image map The Ulinput and UlOutput Components The UIInput component displays a value to the user and allows the user to mod ify this data The most common example is a text field The UIOutput compo nent displays data that cannot be modified The most common example is a label The UIInput and UIOutput components can each be rendered in four ways Table 18 3 lists the renderers of UIInput and UIOutput Recall from Compo nent Rendering Model page 647 that the tags are composed of the component and the ren
96. s content from the body of this tag Container for form tags Encloses all JavaServer Faces tags on the page These tags are used in conjunction with component tags and are therefore explained in other sections of this tutorial Table 18 2 lists the sections that explain how to use specific jsf_core tags 679 se J2EETutorial book Page 680 Thursday June 3 2004 10 26 AM 680 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Table 18 2 Where the jsf_core Tags Are Explained Event handling tags Registering Listeners on Components page 710 Data conversion tags Using the Standard Converters page 705 The UIData Component page 686 and The UIPanel facet Component page 694 loadBundle Using Localized Messages page 703 param Using the outputFormat Tag page 693 and The UISelectItem UISelectItems and UISelectItem lectIt d selectIt D oo Group Components page 700 subview Setting Up a Page page 676 verbatim Using the outputLink Tag page 692 view Setting Up a Page page 676 Using the Standard Validators page 712 and Creating a Validator tags Custom Validator page 750 Using the HIML Component Tags The tags defined by the JavaServer Faces standard HTML render kit tag library represent HTML form controls and other basic HTML elements These controls display data or accept data from the user This data is collected as part of a form and is submitted to
97. s from a Remote J2EE Server 1239 Overview of the Applications 1240 Writing the Application Components 1241 Creating and Packaging the Applications 1241 Deploying the Applications 1244 Running the Application Client 1245 An Application Example That Deploys a Message Driven Bean on Two J2EE Servers 1246 Overview of the Applications 1246 Writing the Application Components 1248 Creating and Packaging the Applications 1249 Deploying the Applications 1251 Running the Application Client 1252 Chapter 35 The Coffee Break Application 1255 Common Code 1256 JAX RPC Coffee Supplier Service 1257 Service Interface 1257 Service Implementation 1258 Publishing the Service in the Registry 1259 Deleting the Service from the Registry 1263 SAAJ Coffee Supplier Service 1265 SAAJ Client 1266 SAAJ Service 1274 Coffee Break Server 1280 JSP Pages 1281 JavaBeans Components 1282 RetailPriceListServlet 1284 18 se J2EETutorial book Page xxxi Thursday June 3 2004 10 26 AM CONTENTS Xxxi JavaServer Faces Version of Coffee Break Server 1284 JSP Pages 1285 JavaBeans Components 1288 Resource Configuration 1289 Building Packaging Deploying and Running the Application 1290 Setting the Port 1291 Setting Up the Registry Server 1291 Using the Provided WARs 1292 Building the Common Classes 1292 Building Packaging and Deploying the JAX RPC Service 1292 Building Packaging and Deploying the SAAJ Service 1294 Building Packaging and
98. s the attributes Here is a simple example of a convertDateTime tag from the bookreceipt jsp page lt h outputText value cashier shipDate gt lt f convertDateTime dateStyle full gt lt h outputText gt Here is an example of a date and time that this tag can display Saturday Feb 22 2003 You can also display the same date and time using this tag lt h outputText value cashier shipDate gt lt f convertDateTime pattern EEEEEEEE MMM dd yyyy gt lt h outputText gt 0 se J2EETutorial book Page 708 Thursday June 3 2004 10 26 AM 708 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Table 18 5 convertDateTime Tag Attributes Attribute dateStyle Type Description Defines the format as specified by java text DateFor mat of a date or the date part of a date string Applied only if type is date or both and pattern is not defined Valid values default short medium long and full If no value is specified default is used String or Locale Locale whose predefined styles for dates and times are used during formatting or parsing If not specified the Locale returned by FacesContext getLocale will be used pattern Custom formatting pattern that determines how the date time string should be formatted and parsed If this attribute is spec ified dateStyle timeStyle and type attributes are ignored timeStyle Defines the format as specified by java text DateFor
99. sents the String that appears in the drop down menu component on the page The itemValue and itemLabel attributes are value binding enabled meaning that they can use value binding expressions to refer to values in external objects They can also define literal values as shown in the example selectOneMenu tag Using Localized Messages All data and messages in the Duke s Bookstore application have been com pletely localized for Spanish French German and American English Performing 18 se J2EETutorial book Page 704 Thursday June 3 2004 10 26 AM 704 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES Localization page 741 explains how to produce the localized messages as well as how to localize dynamic data and messages The image map on the first page allows you to select your preferred locale See Chapter 20 for information on how the image map custom component was created This section explains how to use localized static data and messages for JavaSer ver Faces applications If you are not familiar with the basics of localizing Web applications see Chapter 22 Localized static data can be included in a page by using the loadBund1e tag defined in jsf_core t1d Follow these steps 1 Reference a ResourceBundle from the page 2 Reference the localized message located within the bundle A ResourceBundle contains a set of localized messages For more information about resource bundles see http java su
100. t Scripting Elements 623 TLD Elements 623 Tag Handlers 623 Tags with Bodies 626 Cooperating Tags 627 Tags That Define Variables 629 Chapter 17 JavaServer Faces Technology 631 JavaServer Faces Technology Benefits 633 What Is a JavaServer Faces Application 633 Framework Roles 634 A Simple JavaServer Faces Application 635 Steps in the Development Process 635 Creating the Pages 638 18 se J2EETutorial book Page xix Thursday June 3 2004 10 26 AM CONTENTS xix Defining Page Navigation 640 Developing the Beans 642 Adding Managed Bean Declarations 643 User Interface Component Model 644 User Interface Component Classes 645 Component Rendering Model 647 Conversion Model 651 Event and Listener Model 652 Validation Model 654 Navigation Model 654 Backing Bean Management 656 How the Pieces Fit Together 659 The Life Cycle of a JavaServer Faces Page 662 Request Processing Life Cycle Scenarios 663 Standard Request Processing Life Cycle 664 Further Information 669 Chapter 18 Using JavaServer Faces Technology in JSP POSS RER eee hese a 671 The Example JavaServer Faces Application 672 Setting Up a Page 676 Using the Core Tags 678 Using the HTML Component Tags 680 UI Component Tag Attributes 681 The UIForm Component 683 The UIColumn Component 684 The UICommand Component 684 The UIData Component 686 The UIGraphic Component 690 The Ullnput and UlOutput Components 690 The UIPanel Component 694 The UlSel
101. t h outputText value bundle English gt lt h commandLink gt This tag will render the following HTML lt a id _id3 NAmerica href onclick document forms _id3 _id3 NAmerica value _id3 NAmerica document forms _id3 submitQ return false gt English lt a gt Note Notice that the commandLink tag will render JavaScript If you use this tag make sure your browser is JavaScript enabled The UlData Component The UIData component supports data binding to a collection of data objects It does the work of iterating over each record in the data source The standard Table renderer displays the data as an HTML table The UIColumn component represents a column of data within the table Here is a portion of the dataTable tag used by the bookshowcart jsp page of the Duke s Bookstore example lt h dataTable id items columnClasses list column center list column left Jist column right list column center footerClass list footer headerClass 1ist header rowClasses list row even 1ist row odd styleClass list background value cart items var item gt o 18 J2EETutorial book Page 687 Thursday June 3 2004 10 26 AM USING THE HTML COMPONENT TAGS 687 lt h column gt lt f facet name header gt lt h outputText value bundle ItemQuantity gt lt f facet gt lt h inputText id quantity size 4 value item quantity gt lt h inputText gt
102. tag which is defined in the jsf_core TLD lt f view gt other faces tags possibly mixed with other content lt f view gt You can enclose other content including HTML and other JSP tags within the view tag but all JavaServer Faces tags must be enclosed within the view tag The view tag has an optional locale attribute If this attribute is present its value overrides the Locale stored in the UIViewRoot This value is specified as a String and must be of this form language _ country _ variant The language country and variant parts of the expression are as specified in java util Locale A typical JSP page includes a form which is submitted when a button or hyper link on the page is clicked For the data of other components on the page to be submitted with the form the tags representing the components must be nested inside the form tag See The UIForm Component page 683 for more details on using the form tag If you want to include a page containing JavaServer Faces tags within another JSP page which could also contain JavaServer Faces tags you must enclose the entire nested page in a subview tag You can add the subview tag on the parent page and nest a jsp include inside it to include the page lt f subview id myNestedPage gt lt jsp include page theNestedPage jsp gt lt f subvi ew gt You can also include the subview tag inside the nested page but it must enclose all the JavaServ
103. ter Encoding Further Information What Is an Enterprise Bean Benefits of Enterprise Beans When to Use Enterprise Beans Types of Enterprise Beans What Is a Session Bean State Management Modes When to Use Session Beans What Is an Entity Bean What Makes Entity Beans Different from Session Beans Container Managed Persistence When to Use Entity Beans What Is a Message Driven Bean What Makes Message Driven Beans Different from Session and Entity Beans When to Use Message Driven Beans Defining Client Access with Interfaces Remote Clients Local Clients Local Interfaces and Container Managed Relationships Deciding on Remote or Local Access o 808 810 811 812 816 817 819 820 821 821 822 823 823 823 824 827 829 830 830 830 831 831 832 833 833 835 838 838 838 840 840 840 841 842 842 18 se J2EETutorial book Page xxiii Thursday June 3 2004 10 26 AM CONTENTS xxiii Web Service Clients 843 Method Parameters and Access 844 The Contents of an Enterprise Bean 845 Naming Conventions for Enterprise Beans 846 The Life Cycles of Enterprise Beans 847 The Life Cycle of a Stateful Session Bean 847 The Life Cycle of a Stateless Session Bean 848 The Life Cycle of an Entity Bean 848 The Life Cycle of a Message Driven Bean 850 Further Information 851 Chapter 24 Getting Started with Enterprise Beans 853 Creating the J2EE Application 854 Creating the Enterprise Bean 854 Coding the Ente
104. ters on custom tags and the Coffee Break and Duke s Bank applications use a template tag library that first appeared in Designing Enterprise Applica tions with the J2EE Platform Second Edition Inderjeet Singh et al Addison Wesley 2002 The JavaServer Faces technology and JSP Documents chapters benefited greatly from the invaluable documentation reviews and example code contributions of these engineers Ed Burns Justyna Horwat Roger Kitain Jan Luehe Craig McClanahan Raj Premkumar Mark Roth and especially Jayashri Visvanathan The OrderApp example application described in the Container Managed Persis tence chapter was coded by Marina Vatkina with contributions from Markus Fuchs Rochelle Raccah and Deepa Singh Ms Vatkina s JDO CMP team pro vided extensive feedback on the tutorial s discussion of CMP The security chapter writers are indebted to Raja Perumal who was a key con tributor both to the chapter and to the examples Monica Pawlan and Beth Stearns wrote the Overview and J2EE Connector chap ters in the first edition of The J2EE Tutorial and much of that content has been carried forward to the current edition We are extremely grateful to the many internal and external reviewers who pro vided feedback on the tutorial Their feedback helped improve the technical accu racy and presentation of the chapters and eliminate bugs from the examples We would like to thank our manager Alan Sommerer for his support a
105. the server usually when the user clicks a button This section explains how to use each of the component tags shown in Table 17 2 and is organized according to the UIComponent classes from which the tags are derived The next section explains the more important tag attributes that are common to most component tags Please refer to the TLD documentation at http java sun com j2ee javaserverfaces 1 0 docs t1ddocs index html for a complete list of tags and their attributes For each of the components discussed in the following sections Writing Compo nent Properties page 730 explains how to write a bean property bound to a par ticular UI component or its value o se J2EETutorial book Page 681 Thursday June 3 2004 10 26 AM USING THE HTML COMPONENT TAGS UI Component Tag Attributes In general most of the component tags support these attributes e id Uniquely identifies the component e immediate If set to true indicates that any events validation and con version associated with the component should happen in the apply request values phase rather than a later phase e rendered Specifies a condition in which the component should be ren dered If the condition is not satisfied the component is not rendered e style Specifies a Cascading Style Sheet CSS style for the tag e styleClass Specifies a CSS stylesheet class that contains definitions of the styles e value Identifies an external data s
106. tializing Array and List Properties page 799 for more information on configuring collections as beans You can also create the list corresponding to a UISelectMany or UISelectOne component programmatically in the backing bean See Writing Component Properties page 730 for information on how to write a backing bean property corresponding to a UISelectMany or UISelectOne component se J2EETutorial book Page 703 Thursday June 3 2004 10 26 AM USING LOCALIZED MESSAGES 703 The arguments to the SelectItem constructor are e An Object representing the value of the item e A String representing the label that displays in the UISelectMany com ponent on the page e A String representing the description of the item UlSelectltems Properties page 737 describes in more detail how to write a backing bean property for a UISelectItems component Using the selectitem Tag The selectItem tag represents a single item in a list of items Here is the exam ple from Using the selectOneMenu Tag page 699 lt h selectOneMenu id shippingOption required true value cashier shippingOption gt lt f selectItem itemValue 2 itemLabel bundle QuickShip gt lt f selectItem itemValue 5 itemLabel bundle NormalShip gt lt f selectItem itemValue 7 itemLabel bundle SaverShip gt lt h selectOneMenu gt The itemValue attribute represents the default value of the SelectItem instance The itemLabel attribute repre
107. tion s Resource Reference 103 Mapping the Resource Reference to a Data Source 104 Further Information 104 Chapter 4 Java API for XML Processing 105 The JAXP APIs 105 An Overview of the Packages 106 The Simple API for XML APIs 107 The SAX Packages 109 The Document Object Model APIs 110 The DOM Packages 111 The Extensible Stylesheet Language Transformations APIs 111 The XSLT Packages 112 Using the JAXP Libraries 113 Where Do You Go from Here 113 18 se J2EETutorial book Page x Thursday June 3 2004 10 26 AM CONTENTS Simple API for XML When to Use SAX Echoing an XML File with the SAX Parser Creating the Skeleton Importing Classes Setting Up for I O Implementing the ContentHandler Interface Setting up the Parser Writing the Output Spacing the Output Handling Content Events Compiling and Running the Program Checking the Output Identifying the Events Compressing the Output Inspecting the Output Documents and Data Adding Additional Event Handlers Identifying the Document s Location Handling Processing Instructions Summary Handling Errors with the Nonvalidating Parser Displaying Special Characters and CDATA Handling Special Characters Handling Text with XML Style Syntax Handling CDATA and Other Characters Parsing with a DTD DTD s Effect on the Nonvalidating Parser Tracking Ignorable Whitespace Cleanup Empty Elements Revisited Echoing Entity References Echo
108. tplace the J2EE platform has firmly estab lished its position as the standard for enterprise application servers The J2EE Tutorial Second Edition covers the J2EE 1 4 platform and more If you have used the first edition of The J2EETM Tutorial you may notice that the second edition is triple the size This reflects a major expansion in the J2EE plat form and the availability of two upcoming J2EE technologies in the Sun Java System Application Server Platform Edition 8 the software on which the tutorial is based One of the most important additions to the J2EE 1 4 platform is substantial sup port for Web services with the JAX RPC 1 1 API which enables Web service endpoints based on servlets and enterprise beans The platform also contains Web services support APIs for handling XML data streams directly SAAJ and for accessing Web services registries JAXR In addition the J2EE 1 4 platform requires WS I Basic Profile 1 0 This means that in addition to platform indepen dence and complete Web services support the J2EE 1 4 platform offers Web ser vices interoperability The J2EE 1 4 platform contains major enhancements to the Java servlet and JavaServer Pages JSP technologies that are the foundation of the Web tier The tutorial also showcases two exciting new technologies not required by the J2EE 1 4 platform that simplify the task of building J2EE application user interfaces JavaServer Pages Standard Tag Library JSTL and JavaSe
109. udes the event handler and event listener classes mode1 Includes a model bean class renderers Includes the custom renderers resources Includes custom error messages for the custom converter and validator taglib Includes custom tag handler classes util Includes a message factory class validators Includes a custom validator class Chapter 19 describes how to program backing beans custom converters and val idators and event listeners Chapter 20 describes how to program event handlers custom components renderers and tag handlers The source code for the application is located in the lt INSTALL gt j2ee tutorial14 examples web bookstore6 directory A sample bookstore6 war is provided in lt INSTALL gt j2eetutorial14 examples web provided wars To build package deploy and run the example follow these steps 1 Build and package the bookstore common files as described in Duke s Bookstore Examples page 100 Go to lt INSTALL gt j2eetutorial14 examples web bookstore6 and run asant build Start the Sun Java System Application Server Platform Edition 8 Perform all the operations described in Accessing Databases from Web Applications page 100 Start deploytool Create a Web application called bookstore6 by running the New Web Component Wizard Select FileNew Web Component In the New Web Component wizard a Select the Create New Stand Alone WAR Module radio button b In the WAR Location field ente
110. umn Component The UIColumn component represents a column of data in a UIData component While the UIData component is iterating over the rows of data it processes the UIColumn for each row UIColumn has no renderer associated with it and is repre sented on the page with a column tag Here is an example column tag from the bookshowcart jsp page of the Duke s Bookstore example lt h dataTable id items value cart items var item gt lt h column gt lt f facet name header gt lt h outputText value bundle ItemQuantity gt lt f facet gt lt h inputText value item quantity gt lt f validateLongRange minimum 1 gt lt h inputText gt lt h column gt lt h sdataTabl e gt The UIData component in this example iterates through the list of books cart items in the shopping cart and displays their titles authors and prices The column tag shown in the example renders the column that displays text fields that allow customers to change the quantity of each book in the shopping cart Each time UIData iterates through the list of books it renders one cell in each column The UlCommand Component The UICommand component performs an action when it is activated The most common example of such a component is the button This release supports Button and Link as UICommand component renderers o 4 se J2EETutorial book Page 685 Thursday June 3 2004 10 26 AM USING THE HTML COMPONE
111. ursday June 3 2004 10 26 AM 702 USING JAVASERVER FACES TECHNOLOGY IN JSP PAGES The value attribute of the selectItems tag is bound to the newsletters man aged bean which is configured in the application configuration resource file The newsletters managed bean is configured as a list lt managed bean gt lt managed bean name gt news letters lt managed bean name gt lt managed bean class gt java util ArrayList lt managed bean class gt lt managed bean scope gt app1ication lt managed bean scope gt lt list entries gt lt value class gt javax faces model SelectItem lt value class gt lt value gt news letter0 lt value gt lt value gt news letter1 lt value gt lt value gt news letter2 lt value gt lt value gt news letter3 lt value gt lt list entries gt lt managed bean gt lt managed bean gt lt managed bean name gt news letter0 lt managed bean name gt lt managed bean class gt javax faces model SelectItem lt managed bean class gt lt managed bean scope gt none lt managed bean scope gt lt managed property gt lt property name gt label lt property name gt lt value gt Duke s Quarterly lt value gt lt managed property gt lt managed property gt lt property name gt value lt property name gt lt value gt 200 lt value gt lt managed property gt lt managed bean gt As shown in the managed bean element the UISelectItems component is a collection of SelectItem instances See Ini
112. verterlId attribute to the Converter implementation s identifier The application architect provides this identifier when registering the Converter with the application as explained in Registering a Custom Converter page 804 Creating a Custom Converter page 744 explains how a custom converter is implemented The identifier for the CreditCardConverter is creditCardConverter The CreditCardConverter is registered on the ccno component as shown in this tag from the bookcashier jsp page lt h inputText id ccno size 19 converter CreditCardConverter required true gt lt h inputText gt By setting the converter attribute of a component s tag to the converter s identi fier you cause that component s local value to be automatically converted according to the rules specified in the Converter implementation A page author can use the same custom converter with any similar component by simply supplying the Converter implementation s identifier to the converter attribute of the component s tag or to the convertId attribute of the nested con verter tag o 0 se J2EETutorial book Page 725 Thursday June 3 2004 10 26 AM USING CUSTOM OBJECTS 725 Using a Custom Validator To use a custom validator in a JSP page you must nest the validator s custom tag inside the tag of the component whose value you want to be validated by the cus tom validator Here is the formatValidator tag from the ccno fi
113. view The Application Client The Message Driven Bean Class The onMessage Method The ejbCreate and ejbRemove Methods Deploying and Running SimpleMessageApp Creating the Administered Objects Deploying the Application Running the Client Removing the Administered Objects deploytool Tips for Message Driven Beans Specifying the Bean s Type Setting the Message Driven Bean s Characteristics deploytool Tips for Components That Send Messages Setting the Resource References Setting the Message Destination References Setting the Message Destinations Terminology Simplified Syntax Example Queries Simple Finder Queries Finder Queries That Navigate to Related Beans Finder Queries with Other Conditional Expressions Select Queries Full Syntax BNF Symbols BNF Grammar of EJB QL o 991 991 992 1000 1001 1001 1002 1002 4 se J2EETutorial book Page xxvii Thursday June 3 2004 10 26 AM CONTENTS xxvii FROM Clause 1027 Path Expressions 1030 WHERE Clause 1032 SELECT Clause 1040 ORDER BY Clause 1043 EJB QL Restrictions 1044 Chapter 30 Transactions 1045 What Is a Transaction 1045 Container Managed Transactions 1046 Transaction Attributes 1046 Rolling Back a Container Managed Transaction 1050 Synchronizing a Session Bean s Instance Variables 1052 Compiling the BankBean Example 1053 Packaging the BankBean Example 1053 Methods Not Allowed in Container Managed Transactions 1057 Bea
114. zed with a value when the bean is initialized If a component tag s value attribute must refer to a property that is not initial ized in the managed bean configuration the part of the value binding expression after the must match the property name as it is defined in the backing bean See Application Configuration Resource File page 792 for information on how to configure beans in the application configuration resource file Writing Component Properties page 730 explains in more detail how to write the backing bean properties for each of the component types 4 se J2EETutorial book Page 717 Thursday June 3 2004 10 26 AM BINDING COMPONENT VALUES AND INSTANCES TO EXTERNAL DATA SOURCES 717 Binding a Component Value to an Implicit Object One external data source that a value attribute can refer to is an implicit object The bookreceipt jsp page of the Duke s Bookstore application includes a ref erence to an implicit object from a parameter substitution tag lt h outputFormat title thanks value bundle ThankYouParm gt lt f param value sessionScope name gt lt h outputFormat gt This tag gets the name of the customer from the session scope and inserts it into the parameterized message at the key ThankYouParm from the resource bundle For example if the name of the customer is Gwen Canigetit this tag will render Thank you Gwen Canigetit for purchasing your books from us The name tag on the
Download Pdf Manuals
Related Search
Related Contents
Infinity CLASSIA PSW310W User's Manual Document Q110 User Manual F90A/B F90A/B Manual de Instruções - produktinfo.conrad.com DOCU-M0143_30100_AG-MAC PLUS English_French.indd to refer to Ingress User Manual Alliant Energy - Gas Service Manual Nokia X2–00 Bedienungsanleitung LCD UNIT Copyright © All rights reserved.
Failed to retrieve file