FACELETS PAGE LAYOUT RADIO BUTTONS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" page.xhtml "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <h:selectOneRadio value="#{bean1.condiment}> <html xmlns="http://www.w3.org/1999/xhtml" <f:selectItems value="#{bean1.choices}" var="it" xmlns:f="http://java.sun.com/jsf/core" itemLabel="#{it.description}" xmlns:h="http://java.sun.com/jsf/html" itemValue="#{it.productId}"/> xmlns:ui="http://java.sun.com/jsf/facelets"> </h:selectOneRadio> <h:head>...</h:head> <h:body> WEB-INF/classes/com/corejsf/SampleBean.java <h:form> ... public class SampleBean { </h:form> public Collection<Condiment> getChoices() { ...} </h:body> public int getCondiment() { ... } </html> public void setCondiment(int value) { ... } ... TEXT FIELD } WEB-INF/classes/com/corejsf/Condiment.java page.xhtml public class Condiment { public String getDescription() { ... } <h:inputText value="#{bean1.luckyNumber}"> public int getProductId() { ... } } WEB-INF/classes/com/corejsf/SampleBean.java CONVERSION @Named("bean1") // or @ManagedBean(name="bean1") @SessionScoped <h:outputText value="#{bean1.amount}"> public class SampleBean { <f:convertNumber type="currency"/> public int getLuckyNumber() { ... } </h:outputText> public void setLuckyNumber(int value) { ... } ... The number is displayed with currency symbol and } group separator: $1,000.00 VALIDATION BUTTON Using the bean validation framework (JSR 303) public class SampleBean { page.xhtml @Max(1000) private BigDecimal amount; } <h:commandButton value="press me" action="#{bean1.login}"/> Page-level validation and conversion WEB-INF/classes/com/corejsf/SampleBean.java <h:inputText value="#{bean1.amount}" required="true"> public class SampleBean { <f:validateDoubleRange maximum="1000"/> public String login() { </h:inputText> if (...) return "success"; else return "error"; } Error messages ... } The outcomes success and error can be mapped to pages in faces-config.xml. If no mapping is spec ified, the page Amount /success.xhtml or /error.xhtml is displayed. <h:inputText id="amt" label="Amount" value="#{bean1.amount}"/> <h:message for="amt"/> GET REQUESTS <f:metadata> RESOURCES <f:viewParam name="item" value="#{bean1.currentItem}"/> <f:viewParam name="userId" value="#{bean1.user}"/> page.xhtml </f:metadata> <h:outputStylesheet library="css" name="styles.css"/> ... Request parameters set bean properties before the <h:message for="amt" errorClass="errors"> page is rendered. <h:button value="Continue" outcome="#{bean1.continueOutcome}" resources/css/styles.css includeViewParams="true"/> .errors { The getContinueOutcome method is called when the button is font-style: italic; rendered. The view parameters are added to the color: red; request URL. } core J S F AVA ERVER ACES ™ T E HIRD DITION This page intentionally left blank core J S F AVA ERVER ACES ™ T E HIRD DITION DAVID GEARY CAY HORSTMANN Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City 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 the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. 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 information or programs contained herein. This document is provided for information purposes only and the contents hereof are subject to change without notice. This doc- ument is not warranted to be error-free, nor subject to any other warranties or conditions, whether expressed orally or implied in law, including implied warranties and conditions of merchantability or fitness for a particular purpose. We specifically dis- claim any liability with respect to this document and no contractual obligations are formed either directly or indirectly by this document. This document may not be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without our prior written permission. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 [email protected] For sales outside the United States, please contact: International Sales [email protected] Visit us on the Web: informit.com/ph Library of Congress Cataloging-in-Publication Data Geary, David M. Core JavaServer faces / David Geary, Cay Horstmann.—3rd ed. p. cm. Includes index. ISBN 978-0-13-701289-3 (pbk. : alk. paper) 1. JavaServer pages. 2. Web site development. 3. Web sites—Design. I. Horstmann, Cay S., 1959- II. Title. TK5105.8885.J38G433 2010 006.7'8—dc22 2010011569 Copyright © 2010, Oracle and/or its affiliates. All rights reserved. 500 Oracle Parkway, Redwood Shores, CA 94065 All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax: (617) 671-3447 ISBN-13: 978-0-13-701289-3 ISBN-10: 0-13-701289-6 Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan. First printing, May 2010 CCoonntteennttss Preface xv Acknowledgments xix 1 GETTING STARTED 2 Why JavaServer Faces? 3 A Simple Example 4 Ingredients 7 Directory Structure 8 Building a JSF Application 9 Deploying a JSF Application 11 Development Environments for JSF 13 An Analysis of the Sample Application 15 Beans 16 JSF Pages 17 Servlet Configuration 19 A First Glimpse of Ajax 21 JSF Framework Services 24 Behind the Scenes 26 Rendering Pages 27 v vi Contents Decoding Requests 28 The Life Cycle 29 Conclusion 31 2 MANAGED BEANS 32 Definition of a Bean 33 Bean Properties 36 Value Expressions 37 Backing Beans 38 CDI Beans 39 Message Bundles 40 Messages with Variable Parts 42 Setting the Application Locale 43 A Sample Application 45 Bean Scopes 51 Session Scope 52 Request Scope 53 Application Scope 54 Conversation Scope 54 View Scope 55 Custom Scopes 56 Configuring Beans 56 Injecting CDI Beans 56 Injecting Managed Beans 57 Bean Life Cycle Annotations 58 Configuring Managed Beans with XML 58 The Expression Language Syntax 63 Lvalue and Rvalue Modes 63 Using Brackets 64 Map and List Expressions 65 Calling Methods and Functions 66 Resolving the Initial Term 67 Composite Expressions 69 Contents vii Method Expressions 70 Method Expression Parameters 71 Conclusion 71 3 NAVIGATION 72 Static Navigation 73 Dynamic Navigation 74 Mapping Outcomes to View IDs 75 The JavaQuiz Application 77 Redirection 86 Redirection and the Flash 87 RESTful Navigation and Bookmarkable URLs 88 View Parameters 89 GET Request Links 90 Specifying Request Parameters 91 Adding Bookmarkable Links to the Quiz Application 92 Advanced Navigation Rules 96 Wildcards 97 Using from-action 98 Conditional Navigation Cases 99 Dynamic Target View IDs 99 Conclusion 99 4 STANDARD JSF TAGS 100 An Overview of the JSF Core Tags 102 Attributes, Parameters, and Facets 104 An Overview of the JSF HTML Tags 105 Common Attributes 107 Panels 115 The Head, Body, and Form Tags 118 Form Elements and JavaScript 120 Text Fields and Text Areas 123 Hidden Fields 127 viii Contents Using Text Fields and Text Areas 127 Displaying Text and Images 131 Buttons and Links 134 Using Buttons 136 Using Command Links 141 Selection Tags 145 Checkboxes and Radio Buttons 148 Menus and Listboxes 151 Items 153 Messages 171 Conclusion 177 5 FACELETS 178 Facelets Tags 179 Templating with Facelets 181 Building Pages from Common Templates 183 Organizing Your Views 187 Decorators 193 Parameters 195 Custom Tags 195 Components and Fragments 198 Loose Ends 198 <ui:debug> 198 <ui:remove> 200 Handling Whitespace 202 Conclusion 202 6 DATA TABLES 204 The Data Table Tag—h:dataTable 205 A Simple Table 207 h:dataTable Attributes 210 h:column Attributes 211 Headers, Footers, and Captions 212