JSF Tutorial - JSF Bean Based Navigation Example








We can also define a method in managed bean to return a view name.

The following code defines a managed bean named NavigationController with one method named moveToPage1(). moveToPage1() returns the page name.

@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
   public String moveToPage1(){
      return "page1";
   }
}

We call the moveToPage1() method in the h:commandButton action attribute.

Here when Page1 button is clicked, JSF will resolve the view name, page1 as page1.xhtml extension, and find the corresponding view file page1.xhtml in the current directory.

<h:form>
   <h3>Using Managed Bean</h3>
   <h:commandButton action="#{navigationController.moveToPage1}"
   value="Page1" />
</h:form>




Example

The following code is from UserBean.java.

package com.java2s.common;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{
  
  private static final long serialVersionUID = 1L;
  public String moveToPage1(){
    return "demo";
  }
  
  public String moveToPage2(){
    return "page2";
  }
  
}

The following code is from demo.xhtml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html">
 
    <h:body>
      <h2>This is page1.xhtml</h2>
 
    <h:form>
        <h:commandButton action="page2" value="Move to page2.xhtml" />
      <h:commandButton action="#{user.moveToPage2}" 
        value="Move to page2.xhtml by managed bean" />
    </h:form>
 
    </h:body>
</html>

The following code is from page2.xhtml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html">
 
    <h:body>
      <h2>This is page2.xhtml</h2>
 
     <h:form>
           <h:commandButton action="demo" value="Move to demo.xhtml" />
        <h:commandButton action="#{user.moveToPage1}" 
          value="Move to demo.xhtml by managed bean" />
     </h:form>
 
    </h:body>
</html>


Download Implicit-Navigation.zip





To RUN

Copy the generated WAR file from the target folder to Tomcat deployment folder and run Tomcat-Install-folder/bin/startup.bat.

After Tomcat finish starting, type the following URL in the browser address bar.

http://localhost:8080/simple-webapp/demo.xhtml