Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

Writing Bean Properties

Writing Properties Bound to Component Values

UIInput andUIOutput Properties

UIData Properties

UISelectBoolean Properties

UISelectMany Properties

UISelectOne Properties

UISelectItem Properties

UISelectItems Properties

Writing Properties Bound to Component Instances

Writing Properties Bound to Converters, Listeners, or Validators

Performing Localization

Creating a Resource Bundle

Localizing Dynamic Data

Localizing Messages

Creating a Message with a Message Factory

UsingFacesMessage to Create a Message

Creating a Custom Converter

Implementing an Event Listener

Implementing Value-Change Listeners

Implementing Action Listeners

Creating a Custom Validator

Implementing the Validator Interface

Creating a Custom Tag

Writing the Tag Handler

Writing the Tag Library Descriptor

Writing Backing Bean Methods

Writing a Method to Handle Navigation

Writing a Method to Handle an Action Event

Writing a Method to Perform Validation

Writing a Method to Handle a Value-Change Event

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Writing Backing Bean Methods

Methods of a backing bean perform application-specific functions for components on the page.These functions include performing validation on the component’s value, handling action events, handlingvalue-change events, and performing processing associated with navigation.

By using a backing bean to perform these functions, you eliminate the needto implement theValidator interface to handle the validation or theListener interfaceto handle events. Also, by using a backing bean instead of aValidatorimplementation to perform validation, you eliminate the need to create a custom tagfor theValidator implementation.Creating a Custom ValidatorCreating a Custom Validator describes implementing a custom validator.Implementing an Event Listener describes implementinga listener class.

In general, it’s good practice to include these methods in the same backingbean that defines the properties for the components referencing these methods. The reasonis that the methods might need to access the component’s data to determinehow to handle the event or to perform the validation associated with thecomponent.

This section describes the requirements for writing the backing bean methods.

Writing a Method to Handle Navigation

A backing bean method that handles navigation processing, called an action method, mustbe a public method that takes no parameters and returns anObject, whichis the logical outcome that the navigation system uses to determine what pageto display next. This method is referenced using the component tag’saction attribute.

The following action method inCashierBean is invoked when a user clicks theSubmit button on thebookcashier.jsp page. If the user has ordered more than$100 (or 100 euros) worth of books, this method sets therendered propertiesof thefanClub andspecialOffer components totrue. This causes them to bedisplayed on the page the next time the page is rendered.

After setting the components’rendered properties totrue, this method returns the logicaloutcomenull. This causes the JavaServer Faces implementation to re-render thebookcashier.jsppage without creating a new view of the page. If this method wereto returnpurchase (which is the logical outcome to use to advance tobookcashier.jsp, as defined by the application configuration resource file), thebookcashier.jsp page would re-renderwithout retaining the customer’s input. In this case, you want to re-render thepage without clearing the data.

If the user does not purchase more than $100 (or 100 euros)worth of books or thethankYou component has already been rendered, the method returnsreceipt.

The defaultNavigationHandler provided by the JavaServer Faces implementation matches the logical outcome,as well as the starting page (bookcashier.jsp) against the navigation rules in the applicationconfiguration resource file to determine which page to access next. In this case,the JavaServer Faces implementation loads thebookreceipt.jsp page after this method returns.

public String submit() {    ...    if(cart().getTotal() > 100.00 &&         !specialOffer.isRendered())    {        specialOfferText.setRendered(true);        specialOffer.setRendered(true);        return null;    } else if (specialOffer.isRendered() &&         !thankYou.isRendered()){        thankYou.setRendered(true);        return null;    } else {        clear();        return ("receipt");    }}

Typically, an action method will return aString outcome, as shown in theprevious example. Alternatively, you can define anEnum class that encapsulates all possibleoutcome strings and then make an action method return an enum constant, whichrepresents a particular String outcome defined by theEnum class. In this case,the value returned by a call to theEnum class’stoString method must matchthat specified by thefrom-outcome element in the appropriate navigation rule configuration definedin the application configuration file.

The Duke’s Bank example uses anEnum class to encapsulate all logical outcomes:

public enum Navigation  {    main, accountHist, accountList, atm, atmAck, transferFunds,     transferAck, error}

When an action method returns an outcome, it uses the dot notationto reference the outcome from theEnum class:

public Object submit(){    ...    return Navigation.accountHist;}

Referencing a Method That Performs Navigation explains how a component tag references this method.Binding a Component Instance to a Bean Property discusses how thepage author can bind these components to bean properties.Writing Properties Bound to Component Instances discusses how towrite the bean properties to which the components are bound.Configuring Navigation Rules provides moreinformation on configuring navigation rules.

Writing a Method to Handle an Action Event

A backing bean method that handles an action event must be a publicmethod that accepts an action event and returnsvoid. This method is referencedusing the component tag’sactionListener attribute. Only components that implementActionSource can referto this method.

The following backing bean method fromLocaleBean of the Duke’s Bookstore application processesthe event of a user clicking one of the hyperlinks on thechooselocale.jsppage:

public void chooseLocaleFromLink(ActionEvent event) {    String current = event.getComponent().getId();    FacesContext context = FacesContext.getCurrentInstance();    context.getViewRoot().setLocale((Locale)        locales.get(current));}

This method gets the component that generated the event from the event object.Then it gets the component’s ID. The ID indicates a region of theworld. The method matches the ID against aHashMap object that contains thelocales available for the application. Finally, it sets the locale using the selectedvalue from theHashMap object.

Referencing a Method That Handles an Action Event explains how a component tag references this method.

Writing a Method to Perform Validation

Rather than implement theValidator interface to perform validation for a component, youcan include a method in a backing bean to take care of validatinginput for the component.

A backing bean method that performs validation must accept aFacesContext, the componentwhose data must be validated, and the data to be validated, just asthevalidate method of theValidator interface does. A component refers to the backingbean method by using itsvalidator attribute. Only values ofUIInput components orvalues of components that extendUIInput can be validated.

Here is the backing bean method ofCheckoutFormBean from the Coffee Break example:

public void validateEmail(FacesContext context,     UIComponent toValidate, Object value) {        String message = "";    String email = (String) value;    if (email.contains(’@’)) {        ((UIInput)toValidate).setValid(false);        message = CoffeeBreakBean.loadErrorMessage(context,             CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME,            "EMailError");        context.addMessage(toValidate.getClientId(context),            new FacesMessage(message));    }}

ThevalidateEmail method first gets the local value of the component. It thenchecks whether the@ character is contained in the value. If itisn’t, the method sets the component’svalid property tofalse. The method then loadsthe error message and queues it onto theFacesContext instance, associating themessage with the component ID.

SeeReferencing a Method That Performs Validation for information on how a component tag references this method.

Writing a Method to Handle a Value-Change Event

A backing bean that handles a value-change event must be a public methodthat accepts a value-change event and returnsvoid. This method is referenced usingthe component’svalueChangeListener attribute.

The Duke’s Bookstore application does not have any backing bean methods that handlevalue-change events. It does have aValueChangeListener implementation, as explained in theImplementing Value-Change Listeners section.

For illustration, this section explains how to write a backing bean method thatcan replace theValueChangeListener implementation.

As explained inRegistering a Value-Change Listener on a Component, thename component of thebookcashier.jsp page has aValueChangeListener instance registered on it. ThisValueChangeListener instance handles the event of entering avalue in the field corresponding to the component. When the user enters avalue, a value-change event is generated, and theprocessValueChange(ValueChangeEvent) method of theValueChangeListener class is invoked.

Instead of implementingValueChangeListener, you can write a backing bean method to handlethis event. To do this, you move theprocessValueChange(ValueChangeEvent) method from theValueChangeListenerclass, calledNameChanged, to your backing bean.

Here is the backing bean method that processes the event of entering avalue in thename field on thebookcashier.jsp page:

public void processValueChange(ValueChangeEvent event)    throws AbortProcessingException {    if (null != event.getNewValue()) {        FacesContext.getCurrentInstance().            getExternalContext().getSessionMap().                put("name", event.getNewValue());    }}

The page author can make this method handle theValueChangeEvent object emitted byaUIInput component by referencing this method from the component tag’svalueChangeListener attribute. SeeReferencing a Method That Handles a Value-change Event for more information.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp