Designing Web App Navigation with JavaServer Faces
Topics in This Chapter
"Advanced Navigation Issues"
In this short chapter, we discuss how you configure the navigation of your web application. In particular, you will learn how your application can move from one page to the next, depending on user actions and the outcomes of decisions in the business logic.
Consider what happens when the user of a web application fills out a web page. The user might fill in text fields, click on radio buttons, or select list entries.
All of these edits happen inside the user's browser. When the user clicks a button that posts the form data, the changes are transmitted to the server.
At that time, the web application analyzes the user input and must decide which JSF page to use for rendering the response. The navigation handler is responsible for selecting the next JSF page.
In a simple web application, page navigation is static. That is, clicking a particular button always selects a fixed JSF page for rendering the response. You have seen in Chapter 1 how to wire up static navigation between JSF pages in the faces-config.xml file.
You simply give each button an action attribute, for example,
<h:commandButton label="Login" action="login"/>
As you will see in Chapter 4, navigation actions can also be attached to hyperlinks.
The action must match an outcome in a navigation rule:
<navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/welcome.jsp</to-view-id> </navigation-case> </navigation-rule>
This rule simply states that the login action navigates to /welcome.jsp if it occurred inside /index.jsp.
Note that the view ID strings must start with a /. The extension should match the file extension (.jsp), not the URL extension. For example, if you use a from-view-id of /index.faces, then the rule will not work.
If you pick the action strings carefully, you can group multiple navigation rules together. For example, you may have buttons with action logout sprinkled throughout your application's pages. You can have all of these buttons navigate to the logout.jsp page with the single rule
<navigation-rule> <navigation-case> <from-outcome>logout</from-outcome> <to-view-id>/logout.jsp</to-view-id> </navigation-case> </navigation-rule>
This rule applies to all pages because no from-view-id element was specified.
You can merge navigation rules with the same from-view-id, for example,
<navigation-rule> <from-view-id>/index.jsp</from-view-id> <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/welcome.jsp</to-view-id> </navigation-case> <navigation-case> <from-outcome>signup</from-outcome> <to-view-id>/newuser.jsp</to-view-id> </navigation-case> </navigation-rule>
This merging seems like a good idea, even though it is not required.
If no navigation rule matches a given action, then the current page is simply redisplayed.