ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Handling Events in JavaServer Faces, Part 1
Pages: 1, 2, 3

Using an Action Method and the Default ActionListener

The UICommand component supports method bindings for two types of methods: action methods and action listener methods. Either type can be used to process an ActionEvent, but the action method type is the most commonly used. An action method has no parameters and returns a String value called the action outcome. The outcome is typically "success" if everything went as planned, and "error" or "failure" if there was a problem. The outcome value can affect which view is displayed next, which we get back to in Chapter 9. In a JSP page, you can use the action attribute with a method binding expression to bind a UICommand component to an action method, as shown in Example 8-1.

As you know from the earlier discussions, an ActionEvent is handled by a listener that implements the ActionListener interface, so there must be something else going on to invoke the action method. The missing piece is called the default ActionListener. This is a listener that is provided by the JSF implementation [1] to make it easier to handle events. When a UICommand component is asked to fire an ActionEvent, it first notifies all regular listeners attached to the component, if any. Then it checks if it's been configured with an action method binding. If so, it creates an instance of the default ActionListener and asks it to handle the event. The default ActionListener evaluates the action method binding and invokes the method. As hinted at earlier, the default ActionListener uses the action outcome value to decide which view to use for the response. All of this happens behind the scenes, so you just have to write the action method and bind it to the component.

Example 8-2 shows the add() action method bound to the Add button in Example 8-1.

Example 8-2. The EntryHandler add action method

package com.mycompany.expense;
...

public class EntryHandler {
    private ReportHandler reportHandler;
    private ReportEntry currentEntry;
    ...

    public String add( ) {
        return reportHandler.addEntry(currentEntry);
    }
    ...
}

The add() method is very simple: it just relays the call to the ReportHandler, which is in charge of accessing the current report, passing on the current entry as an argument to the addEntry() method.

So the meat is in the ReportHandleraddEntry() method, shown in Example 8-3.

Example 8-3. The ReportHandler addEntry( ) method

package com.mycompany.expense;

import javax.faces.application.Application;
import javax.faces.application.MessageResources;
import javax.faces.application.Message;
import javax.faces.context.FacesContext;
...

public class ReportHandler {
    private ReportRegistry registry;
    private Rules rules;
    private Report currentReport;
    private String currentUser;
    private boolean isManager;

    ...
    public String addEntry(ReportEntry entry) {
        try {
            refreshCache( );
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage( ));
            return "error";
        }

        if (!rules.canEdit(currentUser, isManager, currentReport)) {
            addMessage("report_no_edit_access", null);
            return "error";
        }

        String outcome = "success";
        currentReport.addEntry(entry);
        try {
            saveReport( );
        }
        catch (RegistryException e) {
            currentReport.removeEntry(entry.getId( ));
            addMessage("registry_error", e.getMessage( ));
            outcome = "error";
        }
        return outcome;
    }

The addEntry() method first calls a method named refreshCache( ) to ensure it has the most recent copy of the current report, in case some other user has modified it:

    private void refreshCache( ) throws RegistryException {
        if (!isReportNew( )) {
            setCurrentReport(registry.getReport(currentReport.getId( )));
        }
    }

    private void setCurrentReport(Report report) {
        currentReport = report;
        entriesModel = null;
    }

If the refresh fails, the addEntry() method adds an error message to the JSF message list and returns "error" as the outcome. Next, it checks that the current user is allowed to edit the current report by calling the canEdit() method implemented by the Rules class we looked at in Chapter 6. If the answer is "no", it adds another error message to the list.

If the user has write access, the entry is added to the current report by calling the addEntry() method on the current Report instance and the updated report is saved in the registry by calling saveReport():

    private void saveReport( ) throws RegistryException {
        if (isReportNew( )) {
            currentReport.setStatus(Report.STATUS_OPEN);
            registry.addReport(currentReport);
        }
        else {
            registry.updateReport(currentReport);
        }
        entriesModel = null;
    }

The saveReport() method adds the report to the registry if it's new (i.e., it hasn't been saved yet) or updates the registry version of the report if it's already in the registry.

Saving the report may fail, and if it does, the addEntry( ) method restores the local copy of the current report to its previous state by removing the entry it just added, and adds an error message to the list as before.

All error messages are added to the JSF message list by the addMessage() method:

    private void addMessage(String messageKey, Object param) {
        FacesContext context = FacesContext.getCurrentInstance( );
        Application application = context.getApplication( );
        String messageBundleName = application.getMessageBundle( );
        Locale locale = context.getViewRoot( ).getLocale( );
        ResourceBundle rb = 
            ResourceBundle.getBundle(messageBundleName, locale);
        String msgPattern = rb.getString(messageKey);
        String msg = msgPattern;
        if (param != null) {
            Object[] params = {param};
            msg = MessageFormat.format(msgPattern, params);
        }
        FacesMessage facesMsg = 
            new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
        context.addMessage(null, facesMsg);
    }

The only difference compared to the code we used in Chapter 7 is that instead of throwing an exception that contains the FacesMessage instance, and relying on the component to add it to the message queue, I use the FacesContextaddMessage() method to queue the message myself. The first addMessage( ) argument takes a component's client ID. This must be used for a message that is associated with a specific component instance. Here I use a null value instead, which means that the message is an application-level message. If you look at Example 8-1, there's an <h:messages> action element at the bottom of the page, just before the entries loop, with a globalOnly attribute set to true. Configured this way, the action displays only application-level error messages. The component-specific messages are displayed by <h:message> actions for each component, just as before.

Using an Action Listener Method or Instance

In most cases, you don't need access to the actual ActionEvent in order to do the right thing, because each component can be bound to a separate action method that implements component-specific behavior. The exception is when one method needs to handle events fired by multiple components, but that turns out to be a very rare case. In fact, there's nothing in the sample application that requires this, and I'm hard pressed to come up with any good use case for it. Even so, the JSF specification supports two alternatives to the action method that provides access to the ActionEvent, in case you do need it.

The first alternative is the action listener method binding, defined by the actionListener attribute in a JSP page:

<h:commandButton value="Add"
  actionListener="#{entryHandler.handleAdd}" />

An action listener method has the exact same signature as the ActionListenerprocessAction() method we looked at earlier; it takes an ActionEvent argument and has a void return type:

public void processAction(ActionEvent e) throws AbortProcessingException {
    UIComponent myCommand = e.getComponent( );
    // Do whatever you need to do depending on which component fired
    // the event
    ...
}

Any object available as a JSF EL expression variable can implement the action listener method, but you can bind a component only to one action listener method. If you need to use more than one listener to handle the same event—maybe one that logs the event and another that really acts on it—you can attach as many ActionListener instances as you want to the component. The JSF core tag library includes an action element that makes this easy to do in a JSP page:

<h:commandButton value="Add">
  <f:actionListener type="com.mycompany.LogEventListener" />
  <f:actionListener type="com.mycompany.HandleAddListener" />
</h:commandButton>

The <f:actionListener> action creates an instance of the class specified by the type attribute and calls the addActionListener() method on the UICommand component.

Specifying When to Fire an Event

So far, I've told you how to bind a component to an event handling method, but I haven't let you in yet on the secret of how an ActionEvent can be made to fire either at the end of the Apply Request Value phase or in the Invoke Application phase.

There are different ways to solve this problem, but the specification group decided to go with an approach in which the source component decides when the event should be processed, with a little bit of help from the application developer. Here's how it works. The FacesEvent class—which all JSF events must extend either directly or through one of the standard subclasses, such as ActionEvent—defines a property named phaseId:

package javax.faces.event;

import java.util.EventObject;
...
public abstract class FacesEvent extends EventObject {
    private PhaseId phaseId = PhaseId.ANY_PHASE;

    public PhaseId getPhaseId( ) {
        return phaseId;
    }

    public void setPhaseId(PhaseId phaseId) {
        this.phaseId = phaseId;
    }
    ...
}

The phaseId property data type is PhaseId, which is a type-safe enumeration containing one value per request processing lifecycle phase: PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS, PhaseId.UPDATE_MODEL_VALUES, PhaseId.INVOKE_APPLICATION, PhaseId.RENDER_RESPONSE, or PhaseId.ANY_PHASE. The PhaseId.ANY_PHASE value means "process the event in the phase where it was queued," and it's the default value for the phaseId property.

So even though UICommand always queues an ActionEvent in the Apply Request Values phase, it sets the phaseId to PhaseId.INVOKE_APPLICATION to delay the event handling unless you tell it that you want to process it immediately. You do so through a UICommand property called immediate. If immediate is true, the phaseId is left unchanged so the event is processed in the Apply Request Values phase. The default ActionListener also tells JSF to proceed directly to the Render Response phase after invoking the action method. The default value for immediate is false, because the ActionEvent is typically used to invoke backend code.

Most of the logic for keeping track of the phase in which an event is to be processed is implemented by the UIViewRoot component that sits at the top of the component tree. At the end of each phase, UIViewRoot goes through the event queue and calls the broadcast() method on all event source components. It starts with all events with phaseId set to PhaseId.ANY_PHASE and then the events queued for the current phase. It continues until there are no more events with these phaseId values in the queue, so if processing one event leads to a new event, the new event is also processed, as long as it's for a matching phase.


Footnotes

[1] As is true for pretty much everything in JSF, an application can define a customized default ActionListener if needed.


Hans Bergsten is the founder of Gefion Software and author of O'Reilly's JavaServer Pages, 3rd Edition.


View catalog information for JavaServer Faces

Return to ONJava.com.