1. Trang chủ
  2. » Công Nghệ Thông Tin

OReilly javaserver faces apr 2004 ISBN 0596005393

1,4K 480 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 1.358
Dung lượng 5,11 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Chapter 8, Handling Events Explains how to deal with different types of events triggered by clicking on buttons and links or changing input components values, and how these events may af

Trang 1

construct the HTML on the front end; how to create the user interface components that

connect the front end to your business

friendly; and how to create the deployment

Trang 2

objects; how to write a back-end that's JSF-descriptors that tie everything together This book is a complete guide to the crucial new JSF technology.

Trang 3

Section 1.4 What You Need to Get Started

Trang 4

Chapter 2 JSF Development Process Overview

Section 2.1 Developing an Application with a JSF-Based User Interface Section 2.2 Developing the Application Backend

Section 4.4 JavaServer Pages

Section 4.5 Accessing Application Data

Chapter 5 Developing the Business Logic and Setting Up Authentication Section 5.1 Sample Application Overview

Trang 5

Section 9.3 Returning a JSF View Response to a Non-JSF Request Chapter 10 Working with Tabular Data

Trang 7

Printed in the United States of America

Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472

O'Reilly Media books may be purchased for educational,

business, or sales promotional use Online editions are also

available for most titles (http://safari.oreilly.com) For moreinformation, contact our corporate/institutional sales

Java™ and all Java-based trademarks and logos are trademarks

or registered trademarks of Sun Microsystems, Inc., in the

United States and other countries Many of the designationsused by manufacturers and sellers to distinguish their productsare claimed as trademarks Where those designations appear inthis book, and O'Reilly Media, Inc was aware of a trademarkclaim, the designations have been printed in caps or initial caps

While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein

Trang 8

JavaServer™ Faces (JSF) is the latest Java™ web applicationtechnology, building on the experience gained from Java

Servlets, JavaServer™ Pages (JSP), and numerous commercialand open source web application frameworks JSF defines anevent-driven, component-based model for web application

development, similar to the model that has been used

successfully for standalone GUI application for years This is anarea that has received a lot of attention from vendors over thelast few years The highly anticipated publication of a Java

Community Process (JCP) developed specification that

addresses this need means that vendors can now focus on

developing first-class development tools and user interfacecomponents based on the JSF specification rather than

reinventing the wheel with proprietary APIs, and you will reapall the benefits of a larger market

Trang 9

This book covers Version 1.0 of the JSF specification, which wasreleased in March 2004

The first four chapters gives an introduction to what JSF has tooffer and how it relates to other Java enterprise technologies.You'll also learn about the fundamentals technologiesHTTP, Javaweb containers, servlets, and JSPand how to install and setup aJava web container

Next, you will learn how to use all the standard JSF componentsand other features (such as input validation, data type

conversion, page navigation, and internationalization), as well

as how to develop customized versions of these items Eachchapter illustrates how to use a specific feature through

stepwise refinement of a sample web application In addition toshowing you what to do, the book also describes what's

happening behind the scenes, helping you gain a deeper

understanding of how JSF works and how to use this technology

in your own applications

The sample application used in this book is an expense reportsystem, where users create, edit, and submit expense reportsfor approval, and managers accept or reject reports It's a

realistic example that guides you through solutions to commonJSF application design problems, such as authenticating users,connecting the business logic objects to the user interface whilestill keeping each aspect decoupled, distinguishing between

user interface events and application events, customizing andlocalizing messages, and building a complete user interface in amodular fashion The last three chapters describe advancedtopics, such as how to develop custom components and custompresentation layers

Trang 10

Developing a web application takes people with different skills,and the JSF specification associates these skill sets with role

responses This book covers the tasks for all these roles

What You Need to Know

I assume that the readers of this book have experience withHTML; consequently, I don't explain the standard HTML

elements used in the examples If you want to learn more about

HTML, I recommend HTML and XHTML: The Definitive Guide by

Chuck Musciano and Bill Kennedy (O'Reilly Media, Inc.) But

even if you're an HTML wiz, this may be your first exposure toweb applications I have therefore included a thorough

introduction to the HTTP protocol that drives all web

applications

I also assume that you're a programmer familiar with Java

programming and object-oriented concepts If that's not thecase, you must learn Java before you continue reading this

book There are plenty of introductory Java books available, for

instance Head First Java (O'Reilly) by Kathy Sierra and Bert

Bates, and Learning Java (O'Reilly) by Patrick Niemeyer and

Trang 11

The JSF specification builds on the Java Servlets specificationand supports using JSP for page layout I've included an

introduction to both these technologies, enough for you tounderstand the examples Before you develop any large, real-world application, though, I recommend that you learn more

about these technologies My own JavaServer Pages (O'Reilly) and Java Servlet Programming by Jason Hunter and William

Crawford (O'Reilly) are two good books for these subjects

Trang 12

The book consists of 15 chapters and 6 appendixes

Chapter 1, Introducing JavaServer Faces

Explains how JSF fits into the big picture of web applicationsand how it compares to alternative technologies

reference implementation

Chapter 4, Servlet and JavaServer Pages Basics

Describes the fundamental HTTP, servlet, and JSP conceptsyou need to know in order to use JSF to its full potential

Chapter 5, Developing the Business Logic and Setting Up

Authentication

Trang 13

Chapter 6, Creating and Rendering Components

Gives a first look under the hood of JSF, focusing on howcomponents are created and rendered at both the API andJSP level

Chapter 7, Calidating Input

Describes how converters and validators are used to

validate user input, and how to develop your own customvalidators and customize error messages

Chapter 8, Handling Events

Explains how to deal with different types of events triggered

by clicking on buttons and links or changing input

components values, and how these events may affect theuser interface or invoke the backend code

Chapter 9, Controlling Navigation

Takes a look at the JSF page navigation feature and how theoutcome of event processing can control which page to

display next

Trang 14

Describes alternative ways to display and edit tabular data,including how to best handle large tables

Chapter 13, Developing Custom Renderers and Other Pluggable

Classes

Describes how to develop custom JSF renderers for

standard components to provide alternative rendering andinput capabilities, and discusses how to replace other

pluggable classes with custom versions

Chapter 14, Developing Custom Components

Shows how to develop custom JSF components in differentways, from simple customization of existing components to

Trang 15

Chapter 15, Developing a Custom Presentation Layer

Describes how JSF supports other presentation layer

technologies besides JSP and how to develop a custom layerinspired by the Tapestry open source product

Appendix D, Infrastructure API Reference

Contains descriptions of all JSF infrastructure classes,

including converters, validators, and error messages

Appendix E, JSF Configuration File Reference

Trang 17

This book contains many examples that demonstrate useful

based web applications The code for all the examples is

techniques for dealing with requirements common to most JSF-contained within the text and is also available for download

from the O'Reilly web site at

http://www.oreilly.com/catalog/jsvrfaces/ You can also

download the example code, ask me questions, and more athttp://www.hansbergsten.com/

The examples use features of the Servlet 2.4 and JSP 2.0

specifications, even though the JSF specification depends on theprevious versions of these specifications: Servlet 2.3 and JSP1.2 I use the latest specifications, released in November 2003,because they make life so much easier in many areas, and Iexpect them to be supported by the major Java web containers

by the time you read this book (or shortly thereafter) All

examples have been tested with the official JSF 1.0 referenceimplementation on Windows ME and Linux (Red Hat Linux 7.2)using Sun's Java 2 SDK, Standard Edition (1.4.2) and Tomcat5.0.18

Trang 18

Italic

Used for pathnames, filenames, program names, compilers,and options, new terms where they are defined, and

Internet addresses such as domain names and URLs

Constant width

Used for anything that appears literally in a JSP page or aJava program, including keywords, data types, constants,method names, variables, class names, interface names,and commands, all JSP and Java code listings, and HTMLdocuments, tags, and attributes

Constant width italic

Used for general placeholders that indicate that an item isreplaced by some actual value in your own program

Constant width bold

Used for text that is typed in code examples by the user

This icon designates a note, which is an important aside to the nearby text.

Trang 19

This icon designates a warning relating to the nearby text.

Trang 20

Please address comments and questions concerning this book tothe publisher:

http://www.oreilly.com/catalog/jsvrfaces/

To comment or ask technical questions about this book, sendemail to:

bookquestions@oreilly.com

For more information about our books, conferences, ResourceCenters, and the O'Reilly Network, see our web site at:

http://www.oreilly.com/

Trang 21

The JSF specification is developed through the Java CommunityProcess (JCP) by representatives from companies large and

small, as well as individuals like me I'd like to thank all JSFExpert Group (EG) members that actively participated in thiseffort, especially Oracle's Adam WinerI'm not sure what we

would have done without you Kudos also to the specificationleads: Ed Burns for keeping track of all the issues we had toresolve and Craig McClanahan for his patience when I lost mine

I'm also grateful to all those who helped me review the bookand spot errors: Adam Winer, Craig McClanahan, Steve Bang,Pierre Delisle, and Janne Andersson; your comments definitelyimproved the material presented in this book Thanks also toDan Malks for connecting my design ideas to the J2EE patterns

copyediting and for being so flexible, and Robert Romano formaking art out of my simple drawings

Many thanks also to my family and friends around the world fortheir support and encouragement, and for Friday nights at theLighthouse with my friends in Vesica Pisces (http://www.vp-unleashed.com/Kelly, Brian, Adam, and Nuss), Rob, Dave,

Becky, James, Tamie, and the rest of the gang Cheers!

Hans Bergsten

Trang 22

Over the last few years, Java has established itself as the

leading technology for web application development Developersare using technologies like servlets and JSP to develop scalableand robust browser-based user interfaces for countless

applications with great success But as web applications becomemore complex, some developers are longing for the good ol'days of traditional graphical user interface (GUI) frameworkswith rich, powerful user interface widgets and event-driven

development models Servlets and JSP have served us well, butHTTP's stateless nature and simple, coarse-grained

have developed frameworks that mimic traditional GUI

frameworks as far as possible Some notable examples are

Enhydra's Barracuda, Apache's Tapestry, Oracle's UIX, and

Sun's JATO In the spring of 2001, a Java Community Process(JCP) group was formed with representatives from most of

these efforts (including yours truly) to come up with a standardsolution that all frameworks can use The result is JavaServerFaces; the 1.0 version of the specification was released in March2004

Trang 23

JavaServer Faces (JSF) simplifies development of sophisticatedweb application user interfaces, primarily by defining a userinterface component model tied to a well-defined request

processing lifecycle This allows:

Java programmers to develop the application backend

without worrying about HTTP details and integrate it withthe user interface through a familiar event-driven modelwith type-safe interfaces

Page Authors without programming knowledge to work withthe user interface "look and feel" aspects by assemblingcomponents that encapsulate all user interaction

logicthereby minimizing the need for program logic

embedded directly in the user interface pages

Vendors to develop powerful tools for both frontend andbackend development

More specifically, JSF is a specification with implementationsoffered by multiple vendors It defines a set of user interface(UI) componentsbasically, a one-to-one mapping to the HTMLform element set plus a few extrasthat can be used right out ofthe box, as well as an Application Programming Interface (API)for extending the standard components or developing brandnew components Validators attached to the components

validate user input, which is then automatically propagated toapplication objects Event handlers are triggered by user

actions, such as clicking on a button or a link, and can changethe state of other components or invoke backend applicationcode The outcome of the event processing controls which page

is displayed next, with help from a pluggable navigation

Trang 24

While HTML is the markup language of choice for most web

applications todayand used for most examples in this bookJSF isnot limited to HTML or any other markup language Renderersthat are separate from the UI components control the actualmarkup sent to the client, so the same UI component coupledwith different renderers can produce very different outputforinstance, either HTML and WML elements If you're familiar withSwing, think "pluggable look and feel" (PLAF)

JSF gives you lots of flexibility in how you actually develop theuser interface All JSF implementations are required to supportJavaServer Pages (JSP) as a presentation layer technology, withJSF components represented by JSP custom action elements

(also commonly known as custom tags) The JSF API, however,

is flexible enough to support other presentation technologiesbesides JSP For instance, you can use pure Java code to createJSF components, which is similar to how a Swing UI is

developed Alternatively, you can bind JSF components to nodes

in templates described by plain HTML files, the approach

explored by projects such as Barracuda/XMLC and Tapestry Iuse the JSP layer for most examples in this book because it'sthe only approach that's completely specified in JSF 1.0, but Ialso show examples of other approaches

If you've developed Java web applications for some time, you'veprobably heard of (and have likely used) application frameworkslike Apache Struts (http://jakarta.apache.org/struts/) or

Maverick (http://mav.sourceforge.net/) Even though JSF

overlaps a bit with the features offered by frameworks like

these (for instance in the areas of validation and navigation

support), it's also designed to play well with them I discuss theoptions available for Struts applications to use a JSF user

interface in Chapter 12, so you'll see exactly how JSF fits

together with this popular application framework

Trang 25

Technologies?

JSF brings a component-based model to web application

development that is similar to the model that's been used instandalone GUI applications for years Let's look at some of theadvantages this gives you compared to more traditional webapplication technologies

1.2.1 Less Code in the User Interface Templates

Java web applications user interfaces have typically been

implemented as a set of JSP pages (or pages for similar

template-engine technologies, such as Velocity or FreeMarker),where static content (e.g., text and HTML elements for layout)

is mixed with elements that generate dynamic content when thepage is processed A problem with this approach is that the

pages often end up with logic for maintaining the user interfacestatefor instance, code for marking checkboxes and list items asselected and for displaying current values in input fields

When you use JSF with JSP as the presentation layer

technology, special elements (JSP custom actions) represent theJSF components Here's a snippet of a page with a form

Trang 26

specified by the value attribute in this example) When the

response is rendered, JSF uses the list to check off the

Trang 30

Figure 1-1 A complex web application user

interface

Trang 31

in this book It contains numerous buttons that are enabled ordisabled depending on who's logged in and the business objectstatus, plus scrollable and sortable tables and input fields thatkeep their previous values between requests The applicationmust also distinguish between different types of requests,

triggered by clicking different buttons and links For an

application like that, JSF really shines

1.2.2 More Modular User Interface Code

The web application architecture most experienced developersrecommend is loosely based on the Model-View-Controller

(MVC) design pattern MVC was first described by Xerox in anumber of papers published in the late 1980s, in conjunctionwith the Smalltalk language This model has since been used forGUI applications developed in all popular programming

languages The basic idea is to separate the application dataand business logic, the presentation of the data, and the

interaction with the data into distinct entities labeled the Model,the View, and the Controller, respectively

The Model represents pure business data and the rules for how

to use this data; it knows nothing about how the data is

Trang 32

While Java web application frameworks like Struts support theMVC model on a high level, it's not supported in the same strict,fine-granular way as in a GUI framework For example, in

Struts, the View is represented by a set of JSP pages, the

Controller by a Struts servlet that delegates the real work toAction classes, and the Model by application classes that

typically interact with a database or some other permanent

storage The interfaces between the different pieces, however,are not defined as a set of specific methods with declared

parameters Instead, control is passed between the pieces usinggeneric methods, and the data the next piece needs is madeavailable through coarse-grained collectionssuch as collections

of all HTTP request parameters, headers, attributes, and so on.Another major difference between a GUI framework and a

typical web application framework is that the latter only

recognizes one type of event: the HTTP request The code thathandles this coarse-grained event has to dig through the

request data to tell if the user has entered new data in any

fields, asked for a different type of presentation by selecting anoption in a menu, ordered a transaction to be completed, orsomething else A GUI framework, on the other hand, is based

on fine-granular events, such as "value changed," "menu itemselected," and "button clicked," with separate event handlersdealing with each event

The JSF MVC design is similar to Swing and other GUI

Trang 33

Figure 1-2 JThe JSF MVC design

The Model is represented by properties of application objects,e.g., a username property on an application object holding userinformation JSF UI components declare what events they canfire, such as "value changed" and "button clicked" events, andexternal event listeners (representing the Controller) attached

to the components handle these events An event listener mayset properties of the JSF componentsfor instance, adjust the set

of rows shown in a tableor invoke backend code that processesthe submitted data (say, verify that a credit card is valid or

update a database) A separate renderer class (representing theView) renders each JSF UI component, making it possible torender instances of the same component type in different ways(e.g., either as a button or a link, or using different markup

languages) just by attaching different renderers

Besides the UI components, JSF also defines artifacts like

validators and converters, each with a well-defined purpose.The end result is a very modular user interface code model that

is easy to maintain, familiar to GUI application developers, andlends itself well to tools support

Trang 34

JSF may not be a good fit for all web applications If you

develop a web site where the dynamic aspects are limited tothings like pulling content from a database, generating dynamicnavigation menus, adding dynamic "cookie trails" to the pages,and other features that just make it easier to maintain the sitecontent and simplify access to different parts of the site, JSF

may be overkill The best fit for JSF is a true web applicationa

web site with a lot of user interactionrather than a web site withsome dynamic content A simple dynamic web site is probablyeasier to implement and maintain using only servlets and JSP,

or even just JSP and the JSP Standard Tag Library (JSTL)

JSF does not necessarily replace current technologies It's acomplement that brings structure and maintainability to theapplication user interface The following sections describe howJSF fits with some established Java web application

technologies

1.3.1 Using JSF with JSP

As you have already seen, JSF plays nicely with JSP In fact, allJSF implementations must support JSP and provide tag librarieswith custom actions for representing the standard JSF UI

components in JSP pages If you're familiar with JSP, adding JSF

to the mix is fairly simple While you can use JSP to developcomplete, simple applications without writing a single line ofJava code, be aware that most JSF applications require eventhandlers and backend logic implemented as Java classes;

hence, you must have a Java programmer handy when you useJSF

Trang 35

Application Frameworks

You may have noticed that I refer to Struts and similar

frameworks as application frameworks, and to JSF as a userinterface framework I do this to emphasize that they have

different objectives An application framework's objective is to

support the development of complete applications; it's

concerned with the Big Picture This type of framework acts as atraffic cop, routing HTTP requests to request handling code andinternal view requests to response rendering code based onmappings between symbolic names and the different types ofapplication components An application framework doesn't careabout details, such as how the user interface is rendered, ormake any distinction between user actions that only affect theuser interface (e.g., asking for the next set of rows to be

displayed in a table) and actions that need to be processed bybackend code (e.g., processing an order on an e-commerce

site) Struts, for instance, can use JSP, Velocity, XSLT, or anyother presentation layer technology to render a response TheStruts servlet just routes requests to application classes thatprocess them and then tell Struts which page to display next

A user interface framework, on the other hand, focuses on the

user interface details and isn't concerned with how the rest ofthe application is implemented It defines a detailed API for

user interface components, for how user actions result in userinterface events and how these events are handled, how thecomponents are tied to the business data they visualize, and soon

With these differences in mind, it should come as no surprisethat it's possible to use JSF with an application framework likeStruts Basically, all requests are processed by JSF until it's

clear that backend code needs to be invoked The control is

then passed on to Struts, and eventually comes back to JSF for

Trang 36

There's some overlap between Struts and JSF, though Bothdefine mechanisms for page navigation and validation, for

instance, but they are so flexible that you can pick and choosewhich should be in charge of these tasks The JSF custom taglibraries also make some of the Struts counterparts obsolete,but the Struts Action and model classes can be used withoutany modification in most cases

based presentation layers that are very similar to JSF Examplesinclude the Barracuda/XMLC and Tapestry open source

Another class of application frameworks includes component-products, as well as a number of commercial products Theseframeworks can be modified to support JSF components in such

a way that it would be almost transparent to the applicationsbuilt on top of them This will likely happen for most commercialproducts and possibly for the open source products if there'senough interest

1.3.3 Using JSF with Enterprise JavaBeans

Enterprise JavaBeans and other J2EE technologies are oftenemployed in complex web applications to support different

types or clients (e.g., HTML browsers, WML browsers, and

standalone GUI applications) with tight security and transactionhandling requirements These technologies are used to

implement the backend code and are not directly tied to theuser interface code As a result, you can use JSF safely withthese technologies

Trang 37

Before we begin, let's quickly run through what you need in

order to work with the examples in this book and develop yourown applications:

A PC or workstation, with a connection to the Internet soyou can download the software you need

A Java 2-compatible Java Software Development Kit (Java 2SDK)

A JSP 2.0-enabled[1] web server, such as Apache Tomcat 5from the Jakarta Project

In addition, there are a variety of other tools and servers thatsupport JSF, from open source projects and commercial

companies IBM, Oracle, and Sun are some of the companiesthat have announced plans for JSF development tools, and

many others are expected to follow Two sites to keep an eye onfor what's available are

http://java.sun.com/j2ee/javaserverfaces/(Sun's JSF site) and

Trang 38

independent JSF resources site run by James Holmes) You maywant to evaluate some of these tools when you're ready to startdeveloping your application, but all you really need to work withthe examples in this book is a regular text editor, such as

Notepad, vi, or Emacs, and of course the Tomcat server

Let's take a closer look at what JSF has to offer The next

chapter starts with an overview of what it takes to use JSF in anapplication

Trang 39

Overview

Imagine building a flight reservation application with a web

interface The user first enters the departure and destinationairports and dates, and preferences such as ticket type, airlines,and number of stops This information is then validated and theuser is presented with matching flight choices When the userpicks his preferred flights, the application ensures that the seatsare available and marks them as reserved, calculates the cost,verifies credit card information, and finalizes the purchase

People who are not computer gurus use applications like this, sothe user interface must be intuitive and easy to use, error

messages must be understandable, and the underlying

problems must be simple to correct For instance, the interfacemay let the user pick the destination airport by first asking for acountry, state, or city name, and then present a selection ofairports matching the criteria, provide calendars for choosingthe dates, and display tables with flights to choose from Andthe interface must be easy to enhance with accumulated userfeedback and usage log analysis The backend code

requirements are also complex: accessing real-time flight

schedules and reservation information, interfacing with creditcard companies, and providing secure tracking of all

transactions

Clearly, this is not an application that can be slapped togetherwithout careful design Applying the Model-View-Controller

(MVC) principles briefly introduced in Chapter 1, we first breakthe application into classes that represent the business dataand logic (the Model, including things like Customer, Airport,Flight, Seat, and so on), the user interface (the View, includingthings like Departure Input Field, Airport List, and so on), andthe code that ties it all together (the Controller)

Trang 40

of the traditional Java server-side technologies like JSP, Velocity,

or plain servlets can render an HTML page with input fields,

selection lists, and tables representing calendars For complexuser interfaces like this, however, the traditional technologiestend to result in pages with so much code that it becomes hard

to make purely visual changes, such as changing the layout of atable

With a JSF-based implementation, separate objects representeach user interface element, each keeping track of its UI state(e.g., brief or detailed display, number of rows to display, andthe current start index) and its application data (e.g., the

selected flight) The user interface objects also know how torender themselves in a way that can be customized based ondeveloper or user settings, or even on the device type makingthe request User actions, such as switching from brief to

detailed display by clicking a button, are represented as eventsthat can be handled either by the user interface object itself or

an external event listener provided by the application developer.This type of event-driven component model has made it easier

to develop very complex user interfaces for standalone

applications over the years and, with a few twists, it simplifiesweb application development as well

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

TỪ KHÓA LIÊN QUAN