16.4 Navigation model

Page navigation is a crucial aspect of all Web applications. The JSF navigation model makes it easy to define page navigation and to handle any additional processing needed to choose the sequence in which pages are loaded.

In the JSF technology, navigation is a set of rules for choosing the next page to be displayed after a UICommand is clicked, that is, a button or hyperlink. These rules are defined in the application configuration resource file.

To handle the simplest navigations, you have to:

Define the rules in the application configuration resource file (see Example 16-16).

Refer to an outcome String from the button or hyperlink component's action attribute. This outcome String is used by the JSF implementation to select the navigation rule to be used. Here is an example of this. Notice that the action attribute is defining the outcome of back:
<hx:commandExButton type="submit" value="Back" action="back">

</hx:commandExButton>

In more complicated applications, you also must provide one or more action methods, which perform some processing to determine which page should be displayed next. For example, a login action can be triggered when the user submits a form by clicking a button. This action can determine whether the login data entered is valid or not, and return a logical outcome String (in this case either "success" or "failure"). The NavigationHandler receives this outcome and determines which page to display next by matching the outcome or the action method reference against the navigation rules in the application configuration resource file. The Example 16-14 shows how to reference a method that implements this kind of dynamic navigation. Example 16-15 shows how this method can be implemented. This method has no parameters and a return type String.

Example 16-14 Invoking an action method to determine the correct outcome

<h:commandButton label="login" action="#{loginController.veryfyUser}"/>

Example 16-15 Deciding the correct outcome

String veryfyUser() {
 if (...)
  return "success";
 else
  return "failure";
}

Each navigation rule defines how to navigate from one particular page to any number of other pages in the application. Each navigation case within a navigation rule defines a target page and either a logical outcome, a reference to an action method, or both. Example 16-16 shows an example navigation rule from the calculator application described in 16.2.2, Defining navigation rules.

Example 16-16 An example navigation rule

<navigation-rule>
 <from-view-id>/welcome.jsp</from-view-id>
 <navigation-case>
  <from-outcome>success</from-outcome>
  <to-view-id>/result.jsp</to-view-id>
 </navigation-case>
</navigation-rule>

This rule states that when a button or hyperlink component on welcome.jsp is activated, the application will navigate from the welcome.jsp page to the result.jsp page if the outcome referenced by the button or hyperlink component's tag is success.


Redbooks
ibm.com/redbooks