10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing Action Listeners<br />

An ActionListener implementation must include a processAction(ActionEvent) method.<br />

<strong>The</strong> processAction(ActionEvent) method processes the specified action event. <strong>The</strong><br />

<strong>Java</strong>Server Faces implementation invokes the processAction(ActionEvent) method when the<br />

ActionEvent occurs.<br />

<strong>The</strong> Duke’s Bookstore application does not use any ActionListener implementations. Instead,<br />

it uses method expressions from actionListener attributes to refer to backing bean methods<br />

that handle events. This section explains how to turn one of these methods into an<br />

ActionListener implementation.<br />

<strong>The</strong> chooselocale.jsp page allows the user to select a locale for the application by clicking on<br />

one of a set of hyperlinks. When the user clicks one of the hyperlinks, an action event is<br />

generated, and the chooseLocaleFromLink(ActionEvent) method of LocaleBean is invoked.<br />

Instead of implementing a bean method to handle this event, you can create a listener<br />

implementation to handle it. To do this, you do the following:<br />

■ Move the chooseLocaleFromLink(ActionEvent) method to a class that implements<br />

ActionListener<br />

■ Rename the method to processAction(ActionEvent)<br />

<strong>The</strong> listener implementation would look something like this:<br />

...<br />

public class LocaleChangeListener extends Object implements<br />

ActionListener {<br />

}<br />

private HashMap locales = null;<br />

public LocaleChangeListener() {<br />

locales = new HashMap(4);<br />

locales.put("NAmerica", new Locale("en", "US"));<br />

locales.put("SAmerica", new Locale("es", "MX"));<br />

locales.put("Germany", new Locale("de", "DE"));<br />

locales.put("France", new Locale("fr", "FR"));<br />

}<br />

public void processAction(ActionEvent event)<br />

throws AbortProcessingException {<br />

}<br />

String current = event.getComponent().getId();<br />

FacesContext context = FacesContext.getCurrentInstance();<br />

context.getViewRoot().setLocale((Locale)<br />

locales.get(current));<br />

Implementing an Event Listener<br />

Chapter 12 • Developing with <strong>Java</strong>Server FacesTechnology 395

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!