Prentice hall core javaserver faces 2nd edition may 2007 ISBN 0131738860

874 55 0
Prentice hall core javaserver faces 2nd edition may 2007 ISBN 0131738860

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Core JavaServer™ Faces, Second Edition by David Geary, Cay Horstmann Publisher: Prentice Hall Pub Date: May 08, 2007 Print ISBN-10: 0-13-173886-0 Print ISBN-13: 978-0-13-173886-7 Pages: 752 Overview JavaServer Faces (JSF) is quickly emerging as the leading solution for rapid user interface development in Java-based server-side applications Now, Core JavaServer™ Faces—the #1 guide to JSF—has been thoroughly updated in this second edition, covering the latest feature enhancements, the powerful Ajax development techniques, and open source innovations that make JSF even more valuable Authors David Geary and Cay Horstmann delve into all facets of JSF 1.2 development, offering systematic best practices for building robust applications, minimizing handcoding, and maximizing productivity Drawing on unsurpassed insider knowledge of the Java platform, they present solutions, hints, tips, and "how-tos" for writing superior JSF 1.2 production code, even if you're new to JSF, JavaServer Pages™, or servlets The second edition's extensive new coverage includes: JSF 1.2's improved alignment with the broader Java EE 5 platform; enhancements to the JSF APIs; controlling Web flow with Shale; and using Facelets to replace JSP with XHTML markup The authors also introduce Ajax development with JSF—from real-time validation and Direct Web Remoting to wrapping Ajax in JSF components and using the popular Ajax4jsf framework This book will help you Automate low-level details and eliminate unnecessary complexity in server-side development Discover JSF best practices, ranging from effective UI design and style sheets to internationalization Use JSF with Tiles to build consistent, reusable user interfaces Leverage external services such as databases, LDAP directories, authentication/authorization, and Web services Use JBoss Seam to greatly simplify development of database-backed applications Implement custom components, converters, and validators Master the JSF 1.2 tag libararies, and extend JSF with additional tag libraries by: ita Copyright 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 Sun Microsystems, Inc., has intellectual property rights relating to implementations of the technology described in this publication In particular, and without limitation, these intellectual property rights may include one or more U.S patents, foreign patents, or pending applications Sun, Sun Microsystems, the Sun logo, J2ME, Solaris, Java, Javadoc, NetBeans, and all Sun and Java based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd 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 PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION SUN MICROSYSTEMS, INC., MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME 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) 3823419, corpsales@pearsontechgroup.com For sales outside the United States, please contact: International Sales, international@pearsoned.com Visit us on the Web: www.prenhallprofessional.com Library of Congress Cataloging-in-Publication Data Geary, David M Core JavaServer faces / David Geary, Cay Horstmann.— 2nd ed p cm Includes bibliographical references and index ISBN-13: 978-0-13-173886-7 (pbk : alk paper) ISBN-10: 0-13-1738860 (pbk : alk paper) 1 JavaServer pages Web site development Web sites— Design I Horstmann, Cay S., 1959- II Title TK5105.8885.J38G433 2007 005.2'768—dc22 2007006830 Copyright © 2007 Sun Microsystems, Inc 4150 Network Circle, Santa Clara, California 95054 U.S.A 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, One Lake Street, Upper Saddle River, NJ 07458; fax, (201) 236-3290 Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana First printing, April 2007 Preface When we heard about JavaServer Faces (JSF) at the 2002 JavaOne conference, we were very excited Both of us had extensive experience with client-side Java programming, and had lived to tell the tale—David in Graphic Java™, and Cay in Core Java™, both published by Sun Microsystems Press When we first tried web programming with servlets and JavaServer Pages (JSP), we found it to be rather unintuitive and tedious JavaServer Faces promised to put a friendly face in front of a web application, allowing programmers to think about text fields and menus instead of fretting over page flips and request parameters Each of us proposed a book project to the publisher, who promptly suggested that we should jointly write the Sun Microsystems Press book on this technology It took the JSF Expert Group (of which David was a member) until 2004 to release the JSF 1.0 specification and reference implementation A bug fix 1.1 release emerged shortly afterwards, and an incremental 1.2 release added a number of cleanups and convenience features in 2006 JSF is now the preeminent server-side Java web framework, and it has fulfilled most of its promises You really can design web user interfaces by putting components on a form and linking them to Java objects, without having to mix code and markup A strong point of JSF is its extensible component model, and a large number of third-party components have become available The flexible design of the framework has allowed it to grow well and accommodate new technologies such as Ajax The framework was designed for tool support, and usable drag-and-drop GUI builders have finally emerged And finally, unlike competing technologies that let you tumble down a deep cliff once you step beyond the glitz, JSF supports the hard stuff—separation of presentation and business logic, navigation, connections with external services, and configuration management We are still excited about JSF, and we hope you will share this excitement when you learn how this technology makes you a more effective web application developer About This Book This book is suitable for web developers whose main focus is user interface design, as well as for programmers who implement reusable components for web applications This is in stark contrast to the official JSF specification, a dense and pompously worded document whose principal audience is framework implementors, as well as long-suffering book authors The first half of the book, extending through Chapter 6, focuses on the JSF tags These tags are similar to HTML form tags They are the basic building blocks for JSF user interfaces No programming is required for use of the tags We assume only basic HTML skills for web pages and standard Java programming for the business logic The first part of the book covers these topics: Setting up your programming environment (Chapter 1) Connecting JSF tags to application logic (Chapter 2) Navigating between pages (Chapter 3) Using the standard JSF tags (Chapters 4 and 5) Converting and validating input (Chapter 6) Starting with Chapter 7, we begin JSF programming in earnest You will learn how to perform advanced tasks, and how to extend the JSF framework Here are the main topics of the second part: Event handling (Chapter 7) Including common content among multiple pages (Chapter 8) Implementing custom components, converters, and validators (Chapter 9) Connecting to databases and other external services (Chapter 10) Ajax (Chapter 11) Open source technologies, with a focus on Facelets, Seam, and Shale (Chapter 12) We end the book with a chapter that aims to answer common questions of the form "How do I ?" (see Chapter 13) We encourage you to have a peek at that chapter as soon as you become comfortable with the basics of JSF There are helpful notes on debugging and logging, and we also give you implementation details and working code for features that are missing from JSF, such as file uploads, popup menus, and a pager component for long tables JSF is built on top of servlets and JSP, but from the point of view of the JSF developer, these technologies merely form the low-level plumbing While it can't hurt to be familiar with other web technologies such as servlets, JSP, or Struts, we do not assume any such knowledge Required Software All software that you need for this book is freely available You need the Java Software Development Kit from Sun Microsystems and an application server that supports JSF, such as the excellent open source GlassFish project The software runs identically on Linux, Mac OS X, Solaris, and Windows We used Java 5 and GlassFish on both Linux and Mac OS X to develop the code examples in the book If you are looking for a development environment that supports JSF development, we can heartily recommend the freely available NetBeans IDE Good JSF support for Eclipse is available from several vendors that sell Eclipse enhancements Web Support The web page for this book is http://corejsf.com It contains The source code for all examples in this book Useful reference material that we felt is more effective in browseable form than in print A list of known errors in the book and the code A form for submitting corrections and suggestions Acknowledgments First and foremost, we'd like to thank Greg Doench, our editor at Prentice Hall, who has shepherded us through this project, never losing his nerve in spite of numerous delays and complications We very much appreciate our reviewers for both editions who have done a splendid job, finding errors and suggesting improvements in various drafts of the manuscript They are: Gail Anderson, Anderson Software Group, Inc Larry Brown, LMBrown.com, Inc Frank Cohen, PushToTest Brian Goetz, Sun Microsystems, Inc Rob Gordon, Crooked Furrow Farm Marty Hall, author of Core Java Servlets and JavaServer Pages Charlie Hunt, Sun Microsystems, Inc Jeff Langr, Langr Software Solutions Bill Lewis, Tufts University Jeff Markham, Markham Software Company Angus McIntyre, IBM Corporation John Muchow, author of Core J2ME Dan Shellman, BearingPoint Sergei Smirnov, principal architect of Exadel JSF Studio com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.j com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.jav com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200) com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117) javax.faces.webapp.FacesServlet.service(FacesServlet.java:198) Here, the subsystem that evaluates the expression language has wrapped code inside an EvaluationException You get to know where the EvaluationEx does not help you—you need the location of the NullPointerException Your next step is to inspect the log files In this case, the log contains a m Caused by: javax.faces.el.EvaluationException: Error getting property 'pass com.corejsf.UserBean: java.lang.NullPointerException at com.sun.faces.el.PropertyResolverImpl.getValue(PropertyResolverI at com.sun.faces.el.impl.ArraySuffix.evaluate(ArraySuffix.java:162) at com.sun.faces.el.impl.ComplexValue.evaluate(ComplexValue.java:14 at com.sun.faces.el.impl.ExpressionEvaluatorImpl.evaluate(Expressio at com.sun.faces.el.ValueBindingImpl.getValue(ValueBindingImpl.java Caused by: java.lang.NullPointerException at com.corejsf.UserBean.getPassword(UserBean.java:12) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessor at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethod at java.lang.reflect.Method.invoke(Method.java:324) at com.sun.faces.el.PropertyResolverImpl.getValue(PropertyResolverI 59 more Finally, information you can use: Line 12 of UserBean.java caused the prob Unfortunately, sometimes the stack trace gives you no useful information a bad case: javax.servlet.ServletException: Cannot find FacesContext org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageCont org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContex org.apache.jsp.index_jsp._jspService(index_jsp.java:78) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:133) javax.servlet.http.HttpServlet.service(HttpServlet.java:856) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.ja org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:301) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:248) javax.servlet.http.HttpServlet.service(HttpServlet.java:856) What caused this error? Misalignment of the planets? No—the problem w http://localhost:8080/login/index.jsp instead of http://localhost:8080/login/ How Do I Avoid the "Stack Trace From Hell"? Most Java programmers expect that the compiler finds their syntax errors develop a JSF application, the compiler only checks your Java source cod JSF pages, managed beans, and configuration files are only detected at time and undecipherable stack traces can be a serious drag on programm Here are some suggestions for detecting errors before you are faced with Use a validating XML editor for JSF pages and configuration files The you misspell element or attribute names, or do not nest elements pro XML editors in Net-Beans do a fine job In Eclipse, XMLBuddy is a rea standalone text editor, find a plug-in, such as nXML for Emacs Use a JSF development environment that understands managed bean language If your IDE supports autocompletion, you will not make typ IDE checks consistency between your JSF pages, managed beans, an errors can be detected before deployment Run the verifier Most application servers can verify a WAR file before find a variety of errors, such as missing classes and syntax errors in y GlassFish, run the command glassfish/bin/verifier appname.war If you use NetBeans, right-click the project and choose "Verify Projec If you use the Sun JSF implementation, force validation of the syntax managed objects that it defines Add these lines to your web.xml com.sun.faces.validateXml true com.sun.faces.verifyObjects true Use a debugger Most IDEs support remote debugging of the applicat breakpoints in managed beans and renderers and, with some IDEs, e can be complex if your IDE does not have predefined support for well worth the effort How Do I "Hot Deploy" My Application? Deploying an application takes time The application server needs to shut application and then unpack, verify, and initialize the new version This ca the developer In hot deployment mode, you copy changed files to a deployment directo senses the change in the file time stamp and incrementally updates the a file The result is much faster turnaround and increased developer If you use an IDE such as NetBeans, it automatically uses hot deploymen build process, you need to understand how to enable hot deployment in y are the rules for GlassFish: Do not create a WAR file Instead, you use directory deployment directory needs to be exactly what it would have been in the WAR file exploded directory Execute the command glassfish/bin/asadmin deploydir buildDirectoryPath to set the directory for your web app and to perform initial deployme the build directory path needs to have the same name as your web By default, GlassFish uses dynamic reloading When the files two seconds and refresh the browser This works well when you chan other changes (such as changes in classes or configuration files) requ trigger redeployment by changing the time stamp of the file example, with the Unix touch command) How Do I Comment Out a Part of a JSF Page? Sometimes, to find out which part of a JSF page causes a stack trace, you honored, divide-and-conquer strategy of commenting out parts of the pag component You may find, to your surprise, that the XML comments > components from being processed Instead, the components are processe enclosed inside >, so that the rendered markup does not show However, this does not help you with debugging since the same exception This behavior seems odd, but keep in mind that most JSF pages are not r non-XML constructs in JSP syntax, such as directives Th tries to parse this mess, and it leaves the XML comment delimiters alone There are two remedies You can use JSP comments delimiters are not processed Alternatively, you can use strict XML for your JSF pages, as described in your JSF pages in a jsp:root tag, then the XML comments will work as exp How Do I Find the Logs? The details depend on your web container GlassFish logs all messages in glassfish/domains/domain1/logs/server.log You can inspect this file in a text GlassFish administration interface Log onto http://localhost:4848/asadmin The default username is adminadmin After logging on, you will see a screen similar to the one Figure 13-18 The GlassFish administration int The first task in the "Common Tasks" window is "Search Log Files" Click viewer (see Figure 13-19) Figure 13-19 The GlassFish log viewer Tomcat 5 keeps logs in the tomcat/logs directory The standard Tomcat lo catalina.out localhost_log.date.log Here date is a date stamp, such as 2003-06-30 The catalina.out file contain System.out and System.err In the default configuration, that includes all log INFO or higher The localhost_log.date.log files contain the logging messag the servlet context Note Both Tomcat and the JSF reference implementation use Apache Co (see http://jakarta.apache.org/commons/logging.html) This loggi bridge to various logging libraries, in particular the java.util.loggin introduced in JDK 1.4 and the Apache Log4J library (http://logging.apache.org/log4j/docs/) There are religious wars o library is better and whether Commons logging is a good idea (see http://www.qos.ch/logging/thinkAgain.html) We must admit to a for java.util.logging It may not be perfect, but it is good enough, standard part of Java How Do I Find Out What Parameters My Page Received? It is often helpful to know what parameters the client sent back to the se submitted Here is a quick and dirty method for logging the request param Insert this snippet of code on top of the JSF file that receives the request Then the logging output will contain entries, such as: Apr 2, 2004 12:50:45 PM org.apache.jsp.welcome_jsp _jspService INFO: name=_id0,value=_id0 Apr 2, 2004 12:50:45 PM org.apache.jsp.welcome_jsp _jspService INFO: name=_id0:_id1,value=me Apr 2, 2004 12:50:45 PM org.apache.jsp.welcome_jsp _jspService INFO: name=_id0:_id2,value=secret Apr 2, 2004 12:50:45 PM org.apache.jsp.welcome_jsp _jspService INFO: name=_id0:_id3,value=Login If you use NetBeans, you can do a lot better than that, by having NetBea (see Figure 13-20) With NetBeans 5.5, follow these steps: Click the "Runtime" tab and expand the "Servers" node Right-click the GlassFish entry and select "Properties" Check "Use HTTP monitor" After you run your application, select the Window -> HTTP Monitor me Figure 13-20 The NetBeans HTTP monito The HTTP monitor displays all traffic between the browser and the web se decodes the requests This is particularly valuable when you develop you How Do I Turn on Logging of the JSF Container? The JSF reference implementation contains copious logging statements w helpful in tracking down problems with your applications With GlassFish, you can conveniently control logging through the adminis onto http://localhost:4848/asadmin The default username is admin adminadmin Then click the "Application Server" node, then the "Logging" tab and then At the bottom of the screen, you will find a table with the title "Additional Properties" Into that table, add an entry with name javax.enterprise.resou FINEST (see Figure 13-21) Figure 13-21 Activating JSF container logging in When you search the logs, be sure to set the logging level to a value fine INFO (see Figure 13-22) Figure 13-22 Setting the logging level in the These settings produce a huge amount of logging information You can fin logging for only those children that interest you The child loggers have s .application .context renderkit .config .lifecycle .taglib For example, if you are interested in monitoring the life cycle phases, the javax.enterprise.resource.webcontainer.jsf.lifecycle to FINEST In Tomcat, you use the standard mechanism of the java.util.logging output Edit the startup script catalina.sh or catalina.bat in the tomcat that sets the variable CATALINA_OPTS to the following parameter definiti -Djava.util.logging.config.file=tomcat/conf/logging.properties In Unix/Linux, use this syntax: CATALINA_OPTS="-Djava.util.logging.config.file=tomcat/conf/logging.proper In Windows, use this syntax: set CATALINA_OPTS=-Djava.util.logging.config.file=tomcat\conf\logging.pro (As always, tomcat denotes the name of the Tomcat installation such 5.5.19 or c:\jakarta-tomcat-5.5.19.) Copy the file logging.properties from the subdirectory jre/lib tomcat/conf directory Edit the file tomcat/conf/logging.properties Locate the line java.util.logging.ConsoleHandler.level = INFO and change INFO to FINEST At the end of the file, add a line javax.enterprise.resource.webcontainer.jsf=FINEST (If you use JSF 1.1, set com.sun.faces.level=FINEST instead.) Restart Tomcat and run a JSF application Then inspect the file To turn off JSF container logging, edit tomcat/conf/logging.properties INFO Caution If Tomcat finds the Apache Log4J library on the class path, then it logging library unless you specifically add the following definition t -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Jdk14 How Do I Debug a Stuck Page? Sometimes, a JSF page seems "stuck." When you click the submit button Here is what you can do to debug such a page: First, double-check the navigation rules to make sure that the page n properly The most common reason for a stuck page is a validation or conversi by placing a tag on the page If you still do not spot the error, install a phase tracker You saw a sim Chapter 7, but for industrial-strength spying, check out FacesTrace fr http://facestrace.sourceforge.net It gives you a visual display of the Figure 13-23 FacesTrace in action FacesTrace is easy to use Add its JAR file and the Commons Logging JAR WEB-INF/lib directory Import the tag library: Then add a tag at the end of your JSF page How Do I Find the Library Source? You can download the library source from http://javaserverfaces.dev.java be very helpful for troubleshooting, and to clarify opaque points of the sp The library code is organized in three directories: jsf-api, the documented API classes whose package names start with jsf-ri, the reference implementation classes whose package names s jsf-tools, the tools that mechanically generate tag handlers and rend To get a complete set of source files, you must run the Ant script in the Copy the file build.properties.template to build.properties Edit the jsf.build.home=path to the javaserverfaces_sources directory container.name=glassfish container.home=path to the GlassFish installation Run ant main The missing source code is produced in the jsf-ri/build/generate Finally, it is sometimes useful to find configuration details of the JSF impl names or class names of the standard components, renderers, converters the files jsf-ri/src/com/sun/faces/jsf-ri-config.xml and jsf-ri/build/classes/ renderkit.xml ... Visit us on the Web: www.prenhallprofessional.com Library of Congress Cataloging-in-Publication Data Geary, David M Core JavaServer faces / David Geary, Cay Horstmann.— 2nd ed p cm Includes bibliographical references and index... p cm Includes bibliographical references and index ISBN- 13: 978-0-13-173886-7 (pbk : alk paper) ISBN- 10: 0-13-1738860 (pbk : alk paper) 1 JavaServer pages Web site development Web sites— Design... Web sites— Design I Horstmann, Cay S., 1959- II Title TK5105.8885.J38G433 2007 005.2'768—dc22 20070 06830 Copyright © 2007 Sun Microsystems, Inc 4150 Network Circle, Santa Clara, California 95054 U.S.A

Ngày đăng: 26/03/2019, 16:07

Mục lục

  • Core JavaServer Faces, 2nd Edition

    • Copyright

    • Preface

    • Acknowledgments

    • Chapter 1. Getting Started

      • Software Installation

      • A Simple Example

      • Sample Application Analysis

      • Development Environments for JSF

      • JSF Framework Services

      • Behind the Scenes

      • Chapter 2. Managed Beans

        • Message Bundles

        • A Sample Application

        • Backing Beans

        • Bean Scopes

        • Configuring Beans

        • The Syntax of Value Expressions

        • Chapter 3. Navigation

          • Dynamic Navigation

          • Advanced Navigation Issues

          • Chapter 4. Standard JSF Tags

            • An Overview of the JSF HTML Tags

            • Forms

            • Text Fields and Text Areas

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan