JSF Tutorial - JSF Implicit Navigation Example








With JSF, we can define the page navigation rules in configuration file faces-config.xml.

We can also put the navigation rules in managed beans.

The following code shows the third option, which is implicit navigation.

JSF 2.0 provides implicit navigation which page can be resolved automatically. We only need to put view name in action attribute and JSF will search the correct view page automatically in the deployed application.

For example, in the following JSF form tag. We set view name in action attribute.

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

<h:form>
   <h:commandButton action="page2" value="Page2" />
</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