Prentice Hall Core JavaServer Faces Jun 2004 ISBN 0131463055

   • core JavaServer™ Faces By ,

  Publisher : Addison Wesley Pub Date : June 15, 2004

  ISBN : 0-13-146305-5 Pages : 552 JavaServer Faces promises to bring rapid user-interface development to server-side

Java. It allows developers to painlessly write server-side applications without worrying about the complexities of dealing with

browsers and Web servers. It also automates

low-level, boring details like control flow and moving code between web forms and business logic. JavaServer Faces was designed to support drag and drop development of server-side applications, but you can also think of it as a conceptual layer on top of servlets and JavaServer Pages (JSP). Experienced JSP developers will find that JavaServer Faces provides much of the plumbing that they currently have to implement by hand. If you already use a server-side framework such as Struts, you will find that JavaServers Faces uses a similar architecture, but is more

flexible and extensible. JavaServer Faces also

comes with server-side components and an

event model, which are fundamentally similar

to the same concepts in Swing. JavaServer Faces is quickly becoming the standard Web-application framework. Core

JavaServer Faces is the one book you need to

  master this powerful and time-saving technology.

  Without assuming knowledge of JSP and servlets, Core JavaServer Faces: shows how to build more robust applications and avoid tedious handcoding answers questions most developers don't even know to ask

demonstrates how to use JSF with Tiles to

build consistent user interfaces automatically provides hints, tips, and explicit "how-to" information that allows you to quickly become more productive explains how to integrate JSF with

databases, use directory services, wireless

apps, and Web services

teaches best practices and good habits like

using style sheets and message bundles covers all of the JSF tags and how to create new tag libraries

   • core JavaServer™ Faces By ,

  Publisher : Addison Wesley Pub Date : June 15, 2004

  ISBN : 0-13-146305-5 Pages : 552

  

  

  

  

  

  

  

Copyright © 2004 Sun Microsystems, Inc

  Printed in the United States of America. 4150 Network Circle, Santa Clara, California 95054 U.S.A.

  

All rights reserved. This product and related documentation are

protected by copyright and distributed under licenses restricting

its use, copying, distribution, and decompilation. No part of this

product or related documentation may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

  RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictions

set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19.

The products described may be protected by one or more U.S. patents, foreign patents, or pending applications. TRADEMARKSHotJava, Java, Java Development Kit, J2EE, JPS, JavaServer Pages, Enterprise JavaBeans, EJB, JDBC, J2SE, Solaris, SPARC, SunOS, and Sunsoft are trademarks of Sun Microsystems, Inc. All other products or services mentioned in this book are the trademarks or service marks of their respective companies or organizations.

  

Prentice Hall PTR offers excellent discounts on this book

when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales, 1-800-382-3419, For sales outside of the U.S., please contact International Sales, 1-317-581- 3793,

  Acquisitions Editor: Gregory G. Doench Editorial Assistant: Raquel Kaplan Production Supervision: Patti Guerrieri Cover Design Director: Jerry Votta Cover Designer: Anthony Gemmellaro Art Director: Gail Cocker-Bogusz Manufacturing Manager: Alexis R. Heydt Marketing Manager: Chris Guzikowski Sun Microsystems Press Publisher: Myrna Rivera First Printing

  Sun Microsystems Press A Prentice Hall Title

About Prentice Hall Professional Technical Reference

  With origins reaching back to the industry's first computer

science publishing program in the 1960s, and formally launched

as its own imprint in 1986, Prentice Hall Professional Technical Reference (PH PTR) has developed into the leading provider of

technical books in the world today. Our editors now publish over

200 books annually, authored by leaders in the fields of computing, engineering, and business. Our roots are firmly planted in the soil that gave rise to the technical revolution. Our bookshelf contains many of the industry's computing and engineering classics: Kernighan and Ritchie's C Programming Language, Nemeth's UNIX System Administration Handbook, Horstmann's Core Java, and Johnson's High-Speed Digital Design.

  

PH PTR acknowledges its auspicious beginnings while it looks to the

future for inspiration. We continue to evolve and break new ground in

publishing by providing today's professionals with tomorrow's solutions.

Preface

  When we heard about JavaServer™ Faces (JSF) at the 2002 Java One conference, we were very excited. Both of us had extensive experience with client-side Java programming, and

had lived to tell the taleDavid 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 is a member) another two years to release the JSF 1.0 specification and reference implementation. This release fulfills many of the

original promises. You really can design web user interfaces by

putting components on a form and linking them to Java objects,

without having to write any code at all. The framework was designed for tool support, and the first batch of drag-and-drop

GUI builders is now emerging. The framework is extensibleyou

are not limited to the standard set of HTML components, and you can even use completely different rendering technologies, to support, for example, wireless devices. And finally, unlike competing technologies that let you tumble down a deep cliff once you step beyond the glitz, JSF supports the hard stuffseparation of presentation and business logic, navigation, connections with external services, and configuration management.

  

Of course, being a 1.0 release, the current version of JSF is far

from perfect. Some of the APIs are awkward. We supply you

  

with utility classes in the com.corejsf.util package to reduce

your pain. Also, there are fewer components than we originally

expected. While JSF has a powerful and convenient data table

component, some useful components such as tabbed panes,

scrollers, file uploads, and so on, were not included for lack of

time. In the book, we show you how to implement these features. Of course, we expect the next release of JSF to remedy many of these shortcomings.

  

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 to the middle of

  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 to use the tags. We only

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 (

   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: Implementing custom converters and validators

   Implementing custom components (

  

   We end the book with a chapter that aims to answer common

questions of the form "How do I….?" 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 1.0, 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, a servlet container such as Tomcat, and, of course, a JSF implementation, such as Sun's reference

implementation. The software runs identically on Linux, Mac OS

X, Solaris, and Windows. We used the 1.4.2 J2SE and Tomcat 5.0.19 on both Linux and Mac OS X to develop the code examples in the book.

  We also expect that integrated environments will become commercially available in the near future.

Web Support

  

The web page for this book is . 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. Thanks to Mary Lou Nohr for editing the

manuscript, and to Patti Guerrieri for her production work. We

very much appreciate our reviewers who have done a splendid

job, finding errors and suggesting improvements in various drafts of the manuscript. They are:

  Larry Brown Frank Cohen, PushToTest Rob Gordon, Crooked Furrow Farm Marty Hall, author of Core Java Servlets and JavaServer Pages Jeff Markham, Markham Software Company Angus McIntyre, IBM Corporation John Muchow, author of Core J2ME

Sergei Smirnov, principal architect of Exadel JSF Studio

Roman Smolgovsky, Flytecomm Stephen Stelting, Sun Microsystems, Inc.

  Christopher Taylor, Nanshu Densetsu Michael Yuan, author of Enterprise J2ME

Finally, thanks to our families and friends who have supported

us through this project and who share our relief that it is finally

completed.

Chapter 1. Getting Started Topics in This Chapter

  

   on page

  

   on page

  

  

  

   on page

  

Why JavaServer Faces

  

Judging from the job advertisements in employment web sites,

there are currently two popular techniques for developing web applications.

  The "rapid development" style, using a visual development environment such as Microsoft ASP.NET.

  The "hard-core coding" style, writing lots of code to support a high-performance back end such as J2EE (the Java 2 Enterprise Edition). As we write this book, development teams face a difficult choice. J2EE is an attractive platform. It is highly scalable. It is

portable to multiple platforms. It is supported by many vendors.

On the other hand, ASP.NET makes it easy to create attractive user interfaces without tedious programming. Of course, programmers want both: a high-performance back end and easy user-interface programming.

  

The promise of JavaServer Faces is to bring rapid user-interface

development to server-side Java. If you are familiar with client-side Java development, you can

think of JSF as "Swing for server-side applications." If you have

experience with JavaServer Pages (JSP), you will find that JSF provides much of the plumbing that JSP developers have to implement by hand. If you already know a server-side framework such as Struts, you will find that JSF uses a similar architecture.

  NOTE

  

You need not know anything about Swing, JSP, or Struts

in order to use this book. We assume basic familiarity only with Java and HTML.

  JSF has these parts: A set of prefabricated UI components An event-driven programming model A component model that enables third-party developers to supply additional components JSF contains all the necessary code for event handling and component organization. Application programmers can be

blissfully ignorant of these details and spend their effort on the

application logic.

For the promise of JSF to be fully realized, we need integrated

development environments that generate JSF applications. As

we write this chapter, these IDEs are just beginning to be developed. For that reason, we start this tutorial chapter by

showing you how to compose a JSF application by hand. When

reading the instructions in this chapter, consider that many of

the steps can and will be automated in the future.

  Software Installation You need the following software packages to get started.

  

The Java SDK 1.4.1 or higher ( )

The Tomcat servlet container . The JavaServer Faces reference implementation ) The sample code for this book, available at

  We assume that you already installed the Java SDK and that you are familiar with the SDK tools. For more information on the Java SDK, see Horstmann & Cornell, Core Java, Sun Microsystems Press, 2003.

  In this chapter, we describe how to use JSF with Tomcat 5.

Tomcat is a servlet container: a program that serves web pages

and executes servletsJava programs that process web requests.

  JavaServer Faces is built on top of the servlet technology, but you need not know anything about servlets to build JSF applications.

Download and unzip Tomcat, the JSF reference implementation,

and the sample code. Place them into directories of your choice.

(As always, it is best to avoid path names with spaces, such as

  c:\Program Files .)

  

In the rest of the book, we refer to these directories as tomcat,

jsf and corejsf-examples. For example, if we refer to

  tomcat /conf/server.xml , you will need to look inside a

directory such as /usr/local/jakarta-tomcat-5.0.19/conf

or c:\jakarta-tomcat-5.0.19\conf .

  If you use Windows, you can choose a Windows installer for

Tomcat instead of the platform-independent ZIP file. Download

and execute the installer program. When you are prompted for

the installation directory, we suggest that you use c:\ tomcat instead of the default location inside the c:\Program Files directory.

NOTE

  

You can run JSF applications with any servlet container

that supports the Servlet 2.3 and JSP 1.2 specifications.

To keep the instructions simple, we cover only Tomcat 5.

If you prefer another servlet container, simply follow the

standard procedure for deploying web applications on

your server.

NOTE

  

You can also obtain JSF from other sources, such as the

J2EE SDK ) or

the Java Web Services Development Pack ( ).

However, these bundles contain many other software

components and have more complex configurations. We

suggest that you move on to more sophisticated

environments after becoming comfortable with Tomcat

and the JSF reference implementation.

  

Now you are ready to get started. Open a command shell and

start Tomcat. On Unix/Linux, you use the command

  tomcat/bin/startup.sh

  (See .) On Windows, launch

  tomcat\bin\startup.bat

  Figure 1-1. Starting Tomcat Alternatively, if you used the Windows installer to install

Tomcat, you can use the "Start Tomcat" menu item in the start

menu. To test that Tomcat runs properly, point your browser to http://localhost:8080. You should see a welcome page (see .

  Figure 1-2. Tomcat Welcome Page

  

You shut down Tomcat with the command

  tomcat/bin/shutdown.sh

  or, on Windows, tomcat\bin\shutdown.bat

  Alternatively, if you used the Windows installer to install

Tomcat, you can shut down the running server by right-clicking

the Tomcat icon in the system tray.

A Simple Example

  Let us move on to a simple example of a JavaServer Faces

application. Our first example starts with a login screen, shown

in .

  

Figure 1-3. A Login Screen

Of course, in a real web application, this screen would be beautified by a skilled graphic artist. The file that describes the login screen is essentially an HTML file with a few additional tagssee . Its visual

appearance can be easily improved by a graphic artist who need

not have any programming skills.

  login/index.jsp Listing 1-1.

  1. <html> 2. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> 3. <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> 4.

  5. <f:view> 6. <head> 7. <title>A Simple JavaServer Faces Application</title> 8. </head> 9. <body> 10. <h:form> 11. <h3>Please enter your name and password.</h3> 12. <table> 13. <tr> 14. <td>Name:</td> 15. <td> 16. <h:inputText value="#{user.name}"/> 17. </td> 18. </tr>

  19. <tr> 20. <td>Password:</td> 21. <td> 22. <h:inputSecret value="#{user.password}"/> 23. </td> 24. </tr> 25. </table> 26. <p> 27. <h:commandButton value="Login" action="login"/> 28. </p> 29. </h:form> 30. </body> 31. </f:view> 32. </html> We discuss the contents of this file in detail later in this chapter.

  For now, note the following points: A number of the tags are standard HTML tags: body , table , and so on.

  Some tags have prefixes, such as f:view and h:inputText .

These are JSF tags. The two declarations declare

  taglib the JSF tag libraries.

  The h:inputText , h:inputSecret , and h:commandButton tags correspond to the text field, password field, and submit button in . The input fields are linked to object properties. For example, the attribute value="#{user.name}" tells the JSF implementation to link the text field with the name property of a user object. We discuss this linkage in more detail later in this chapter. When the user enters the name and password and clicks the login button, a welcome screen appears (see ).

  

Figure 1-4. A Welcome Screen

  

The welcome message contains the user name. The password is

ignored for now. The purpose of this application is, of course, not to impress anyone, but merely to illustrate the various pieces that are necessary to produce a JSF application.

Ingredients

  Our sample application consists of the following ingredients:

Pages that define the login and welcome screens. We call

them and .

  index.jsp welcome.jsp

  A bean that manages the user data (in our case, username and password). A bean is simply a Java class that exposes properties, usually by following a simple naming convention

for the getter and setter methods. The code is in the file

see Note that the class is

  UserBean.java contained inside the package. com.corejsf

  A configuration file for the application that lists bean resources and navigation rules. By default, this file is called

  faces-config.xml .

  Miscellaneous files that are needed to keep the servlet

container happy: the web.xml file and an index.html file that redirects the user to the correct URL for the login page. More advanced JSF applications have the same structure, but they can contain additional Java classes, such as event handlers, validators, and custom components. login/WEB- Listing 1-2.

  INF/classes/com/corejsf/UserBean.java 1. package com.corejsf; 2.

  3. public class UserBean { 4. private String name; 5. private String password; 6.

  7. // PROPERTY: name 8. public String getName() { return name; } 9. public void setName(String newValue) { name = newValue; } 10.

  11. // PROPERTY: password 12. public String getPassword() { return password; } 13. public void setPassword(String newValue) { password = newValue; } 14. }

Directory Structure

  A JSF application is deployed as a WAR file: a zipped file with extension .war and a directory structure that follows a standardized layout: HTML and JSP files

  WEB-INF/

  configuration files

  classes/

  class files

  lib/

  library files For example, the WAR file of our sample application has the

directory structure shown in . Note that the UserBean

class is in the package com.corejsf . The META-INF directory is

automatically produced by the JAR program when the WAR file

is created.

  

Figure 1-5. Directory Structure of the Sample

WAR File

  

To minimize confusion, we package our application source in the

exact same directory structure as a WAR file, except that the

  classes directory contains the source files (see ).

  

Figure 1-6. Directory Structure of the Sample

Application

Build Instructions

  

We now walk you through the steps required for building JSF

applications with your bare hands. At the end of this chapter,

we show you how to automate this process.

  1. Launch a command shell.

  2. Change to the ch1/login/WEB-INF/classes directory inside corejsf-examples, the directory that contains the sample code for this book.

  3. Run the command

  javac com/corejsf/UserBean.java

  (On Windows, use backslashes instead: javac

  com\corejsf\UserBean.java .)

  4. Make a ch1/login/WEB-INF/lib directory. Into that directory, copy the following files:

  jsf/lib/jsf-api.jar jsf/lib/jsf-impl.jar:jsf/lib/jsf-impl.jar tomcat/server/lib/commons-digester.jar tomcat/server/lib/commons-beanutils.jar tomcat/webapps/jsp-examples/WEB-INF/lib/jstl.jar tomcat/webapps/jsp-examples/WEB-INF/lib/standard.jar

  5. Change to the directory.

  ch1/login

  6. Run the command jar cvf login.war.

  (Note the period at the end of the command, indicating the current directory.)

  7. Copy the login.war file to the directory tomcat /webapps .

  8. Now point your browser to http://localhost:8080/login The application should start up at this point.

  TIP If you are very impatient, you can use two shortcuts.

  

Copy the six library JAR files into the tomcat /common/lib

directory and restart the server. Then you don't have to

place the libraries into the WEB-INF/lib directory of your

applications. Moreover, you can bypass the WAR filesimply

copy the entire login directory (including its subdirectories) to the tomcat /webapps directory. Remember to compile the source files in the WEB- INF/classes directory.

  

For more complex programs that reference the JSF libraries, the

compilation step is more complex. Your class path must include the following JAR files:

  tomcat/common/lib/servlet-api.jar tomcat/common/lib/jsp-api.jar jsf/lib/jsf-api.jar jsf/lib/jsf-impl.jar

  A typical compilation command would look like this:

  javac -classpath .:tomcat/common/lib/servlet-api.jar :tomcat/common/lib/jsp-api.jar:jsf/lib/jsf-api.jar com/corejsf/*.java

  The entire command needs to be placed on a single line.

(On Windows, use semicolons to separate the path elements.)

Sample Application Analysis

  

Web applications have two parts: the presentation layer and the

business logic. The presentation layer is concerned with the look of the application. In the context of a browser-based application, the look is determined by the HTML tags that specify layout, fonts, images, and so on. The business logic is implemented in the Java code that determines the behavior of the application.

  Some web technologies intermingle HTML and code. That approach is seductive since it is easy to produce simple

applications in a single file. But for serious applications, mixing

markup and code poses considerable problems. Professional web designers know about graphics design, but they typically rely on tools that translate their vision into HTML. They would certainly not want to deal with embedded code. On the other hand, programmers are notoriously unqualified when it comes to graphic design. (The example programs in this book bear ample evidence.) Thus, for designing professional web applications, it is important to separate the presentation from the business logic. This allows both web designers and programmers to focus on their core competences.

In the context of JSF, the application code is contained in beans,

and the design is contained in web pages. We look at beans first.

Beans

  

A Java bean is a class that exposes properties and events to an environment such as JSF. A property is a named value of a

given type that can be read and/or written. The simplest way to define a property is to use a standard naming convention for the reader and writer methods, namely, the familiar get / set

convention. The first letter of the property name is changed to

upper case in the method names.

For example, the UserBean class has two properties: name and

password , both of type String .

  public class UserBean { public String getName() { . . . } public void setName(String newValue) {. . . } public String getPassword() { . . . } public void setPassword(String newValue) { . . . } . . .

  }

  

The get / set methods can carry out arbitrary actions. In many

cases, they simply get or set an instance field. But they might

also access a database or a JNDI directory.

  NOTE

  

According to the bean specification, it is legal to omit a

read or write method. For example, if getPassword is omitted, then is a write-only property. That password

might indeed be desirable for security reasons. However,

JSF 1.0 deals poorly with this situation. For now, it is best

to give read/write access to all bean properties.

  

In JSF applications, you use beans for all data that needs to be

accessible from a page. The beans are the conduits between the

user interface and the back end of the application.

JSF Pages

  You need a JSF page for each browser screen. Depending on your development environment, JSF pages typically have extension .jsp or . jsf . At the time of this writing, the extension .jsp requires less configuration effort when used

with Tomcat. For that reason, we use the .jsp extension in the

examples of this book.

NOTE

  

The extension of the page files is .jsp or .jsf , whereas

in the preferred configuration, the extension of the page

URLs is .faces . For example, when the browser requests

the URL http://localhost:8080/login/index.faces, the URL

extension .faces is mapped to the file extension .jsp and the servlet container loads the file index.jsp . This process sounds rather byzantine, but it is necessary to implement JSF on top of the servlet technology. Let's have a second look at the first page of our sample application in . The page starts out with the tag library declarations

  <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

  The JSF implementation defines two sets of tags. The core tags are independent of the rendering technology. For example, you need the f:view tag both for HTML pages and for pages that are rendered by a cell phone. The HTML tags generate HTML specific markup. If you want your web application to render pages for an alternative client technology, you must use a different tag library. (We discuss support for alternative client technologies in

  h:inputText and f:view. However, we use f for the core tags and h for the HTML tags.

  

Much of the page is similar to an HTML form. Note the following

differences: All JSF tags are contained inside an f:view tag. Instead of using an HTML form tag, you enclose all of the JSF components inside an h:form tag.

  Instead of using the familiar input HTML tags, use h:inputText , h:inputSecret , and h:commandButton .

  We discuss all standard JSF tags and their attributes in In the first three chapters, we can get by with input fields and command buttons.

  

The input field values are bound to properties of the bean with

name user :

  <h:inputText value="#{user.name}"/>

You will see the definition of the user bean in the next section.

  The #{...} delimiters are explained in . When the page is displayed, the getName method is called to

obtain the current property value. When the page is submitted, the setName method is invoked to set the value that the user entered. The h:commandButton tag has an action attribute whose value is used when specifying navigation rules.

  <h:commandButton value="Login" action="login"/>

  We discuss navigation rules in the next section. The value attribute is the string that is displayed on the button.

  The second JSF page of our application is even simpler than the first. It merely uses the h:outputText tag to display the user namesee .

Listing 1-3. login/welcome.jsp

  1. <html> 2. <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> 3. <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> 4.

  5. <f:view>

  6. <head> 7. <title>A Simple JavaServer Faces Application</title> 8. </head> 9. <body> 10. <h3>

  11. Welcome to JavaServer Faces, 12. <h:outputText value="#{user.name}"/>! 13. </h3> 14. </body> 15. </f:view> 16. </html>

NOTE

  

We use a plain and old-fashioned format for our JSF pages so that they are as

easy to read as possible.

  XML-savvy readers will want to do a better job. First, it is desirable to use proper

  XML for the tag library declarations, eliminating the <%...%> tags. Moreover, you will want to emit a proper DOCTYPE declaration for the generated HTML document. The following format solves both issues:

  <?xml version="1.0" ?> <jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <f:view> <f:verbatim><![CDATA[<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">]]> </f:verbatim> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>A Simple Java Server Faces Application</title> </head> <body> <h:form> . . . </h:form> </body> </html> </f:view> </jsp:root> If you use an XML-aware editor, you should seriously consider this form.

CAUTION

  You sometimes see naive page authors produce documents that start with an HTML DOCTYPE declaration, like this: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <f:view> . . .

  This may have been acceptable at one time, but nowadays, it is quite reprehensible. Plainly, this document is not an "HTML 4.01 Transitional" document. It merely aims to produce such a document. Many XML editors and tools don't take it kindly when you lie about the document type. Therefore, either omit the DOCTYPE altogether or follow the outline given in the preceding note.

  Navigation To complete our JSF application, we need to specify the

  

navigation rules. A navigation rule tells the JSF implementation

which page to send back to the browser after a form has been

submitted. In this case, navigation is simple. When the user clicks the

"Login" button, we want to navigate from the index.jsp page

to welcome.jsp . You specify this navigation rule in the faces-

  config.xml file: <navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/welcome.jsp</to-view-id> </navigation-case> </navigation-rule>

  The from-outcome value matches the action attribute of the command button of the index.jsp page:

  <h:commandButton value="Login" action="login"/>

  

In addition to the navigation rules, the faces-config.xml file

contains the bean definitions. Here is the definition of the user

bean.

  <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class> com.corejsf.UserBean </managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>

  You can use the bean name, user , in the attributes of the user

interface components. For example, index.jsp contains the tag

  <h:inputText value="#{user.name}"/>

  The value attribute refers to the name property of the user

bean. (The #{...} delimiters denote the fact that user.name is

The managed-bean-class tag simply specifies the bean class, in

our case, com.corejsf.UserBean . Finally, the scope is set to

  session . That means that the bean object is available for one

  user across multiple pages. Different users who use the web application are given different instances of the bean object.

   shows the complete faces-config.xml file.

  login/WEB-INF/faces-config.xml Listing 1-4.

  1. <?xml version="1.0"?>

  3. <!DOCTYPE faces-config PUBLIC 4. "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" 5. "http://java.sun.com/dtd/web-facesconfig_1_0.dtd"> 6.

  7. <faces-config> 8. <navigation-rule> 9. <from-view-id>/index.jsp</from-view-id> 10. <navigation-case> 11. <from-outcome>login</from-outcome> 12. <to-view-id>/welcome.jsp</to-view-id> 13. </navigation-case> 14. </navigation-rule> 15.

  16. <managed-bean> 17. <managed-bean-name>user</managed-bean-name> 18. <managed-bean-class>com.corejsf.UserBean</managed-bean-class> 19. <managed-bean-scope>session</managed-bean-scope> 20. </managed-bean>

  21. </faces-config>

Servlet Configuration

  When you deploy a JSF application inside an application server, you need to supply a configuration file named web.xml . Fortunately, you can use the same web.xml file for most JSF applications. shows the file.

  login/WEB-INF/web.xml Listing 1-5.

  1. <?xml version="1.0"?> 2.

  3. <!DOCTYPE web-app PUBLIC 4. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 5. "http://java.sun.com/dtd/web-app_2_3.dtd"> 6.

  7. <web-app> 8. <servlet> 9. <servlet-name>Faces Servlet</servlet-name> 10. <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

  11. <load-on-startup>1</load-on-startup> 12. </servlet> 13.

  14. <servlet-mapping> 15. <servlet-name>Faces Servlet</servlet-name> 16. <url-pattern>*.faces</url-pattern> 17. </servlet-mapping> 18.

  19. <welcome-file-list> 20. <welcome-file>index.html</welcome-file> 21. </welcome-file-list> 22. </web-app> The only remarkable aspect of this file is the servlet mapping.

  

All JSF pages are processed by a special servlet that is a part of

the JSF implementation code. To ensure that the correct servlet

is activated when a JSF page is requested, the JSF URLs have a

special format. In our configuration, they have an extension

  .faces . For example, you cannot simply point your browser to

  http://localhost:8080/login/index.jsp. The URL has to be http://localhost:8080/login/index.faces. The servlet container

uses the servlet mapping rule to activate the JSF servlet, which strips off the faces suffix and loads the index.jsp page.

NOTE

  You can also define a prefix mapping instead of the .faces extension mapping. Use the following directive in your web.xml file: <servlet-mapping>

<servlet-name>Faces Servlet</servlet-name>

<url-pattern>/faces/*</url-pattern> </servlet-mapping> Then use the URL

http://localhost:8080/login/faces/index.jsp. That URL

activates the JSF servlet, which then strips off the faces

prefix and loads the file /login/index.jsp.

NOTE

  If you want to use a .jsf extension for JSF page files, then you need to configure your web application so that it invokes the JSP servlet for files with that extension. In Tomcat, you use the following mapping in the web.xml file:

  <servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> You now need to tell the JSF implementation to map the

  .faces extension of the URLs to the .jsf extension of the associated files.

  <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.jsf</param-value> </context-param> Note that this configuration affects only the web developers, not the users of your web application. The URLs still have a .faces extension or /faces prefix.

  The Welcome File Many web designers rely on web servers to load the index.html or index.jsp page when they are given a directory

  URL. Unfortunately, that mechanism doesn't work smoothly with JSF pages. For example, if a user visits the URL http://localhost:8080/login, then Tomcat should not load

  index.jsp . Doing so would skip the JavaServer Faces processing phase.

  To overcome this issue, you can supply an index.html file that automatically redirects the user to the start of the application, using the proper faces URL. shows such an index file.

  login/index.html Listing 1-6.

  1. <html> 2. <head> 3. <meta http-equiv="Refresh" content= "0; URL=index.faces"/> 4. <title>Start Web Application</title> 5. </head> 6. <body> 7. <p>Please wait for the web application to start.</p> 8. </body> 9. </html>

  

page

NOTE

  The index.html file redirects the browser to the index.faces URL. It is slightly more efficient to use a JSP

forward action instead. Create a page, say, start.jsp ,