JSF 2 comes with a very flexible conditional navigation rule to solve the complex page navigation flow, see the following conditional navigation rule example :
1. JSF Page
A simple JSF page, with a button to move from this page to the payment page.
start.xhtml
##2. Managed Bean
A managed bean to provide sample data to perform the conditional checking in the navigation rule.
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
@ManagedBean
@SessionScoped
public class PaymentController implements Serializable {
private static final long serialVersionUID = 1L;
public boolean registerCompleted = true;
public int orderQty = 99;
//getter and setter methods
}
##3. Conditional Navigation Rule
Normally, you declared the simple navigation rule in the “`faces-config.xml`” like this :
start.xhtml
payment
payment.xhtml
With JSF 2, you can add some conditional checking before it move to the payment page, see following :
##faces-config.xml
This is equal to the following Java code :
if (from-view-id == “start.xhtml”){
if(from-outcome == “payment”){
if(paymentController.orderQty < 100){
return "ordermore";
}else if(paymentController.registerCompleted){
return "payment";
}else{
return "register";
}
}
}
The code should be self explanatory enough.
> Note
> In the conditional navigation rule, the sequence of the navigation rule does affect the navigation flow, always put the highest checking priority in the top.
##4. Testing
Different data sets for testing :
###Example 1
public class PaymentController implements Serializable {
public boolean registerCompleted = true;
public int orderQty = 99;
...
When the button is clicked, it hits the "`paymentController.orderQty < 100`" criteria and move to the "`ordermore.xhtml`" page.
###Example 2
public class PaymentController implements Serializable {
public boolean registerCompleted = true;
public int orderQty = 200;
...
When the button is clicked, it hits the "`paymentController.registerCompleted`" criteria and move to the "`payment.xhtml`" page.
###Example 3
public class PaymentController implements Serializable {
public boolean registerCompleted = false;
public int orderQty = 200;
...
When the button is clicked, it failed all the checking criteria and move to the "`register.xhtml`" page.
##Suggestion
In JSF 2.0, there is no "else" tag in the conditional navigation rule, wish JSF team can include the "`else`" tag in the future release. For example,
start.xhtml
payment
#{paymentController.orderQty < 100}
ordermore.xhtml
#{paymentController.registerCompleted}
payment.xhtml
register.xhtml
Moreover, It should include the multiple conditional checking as well, like this
start.xhtml
payment
#{paymentController.orderQty < 100} && #{paymentController.xxx}
ordermore.xhtml
#{paymentController.registerCompleted}
payment.xhtml
register.xhtml
“`
Thought…
JSF 2 conditional navigation rule, … quite similar with the Spring Web Flow, right? :)