Wednesday, September 26, 2012

All about navigational flows - JSF 2.0

Many tutorial online but most of them are JSF 1.2 and would not work as expected.
Navigational output:
Note: Please pay attention how URL changes
Faces-config.xml this file is by default when you have your project supported with JavaServer Faces 2.0.

If not you can have it by Project Properties Project Facets Check Javaserver Faces



faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
 version="2.0">
 
 
</faces-config>


Navigation without bean Page1.xhtml Page2.xhtml without url change display
Page1.xhtml
<!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"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"> 

<h:head></h:head> 
<body>
    <rich:panel>
        <f:facet name="header">
        Experimenting with JSP navigation
        </f:facet>
  <h:outputText value="This is Page 1" /> 
  <br />
  <br />
  <h:form>
   <h:commandButton action="Page2" id="Button1" value="Navigate to Page2"></h:commandButton>
  </h:form>
  <br />
  <br />
  <h:form>
   <h:commandButton action="Page2?faces-redirect=true" id="Button2" value="Navigate to Page2 with updatedURL"></h:commandButton>
  </h:form>
  <br />
  <br />
  <h:form>
   <h:commandButton action="#{testbean.navigate}" id="Button3" value="Navigate using Bean"></h:commandButton>
  </h:form>
  <br />
  <br />
  <h:form>
   <h:commandButton action="#{testbean.navigate_changeurl}" id="Button4" value="Navigate using Bean and updated URL"></h:commandButton>
  </h:form>
  
 </rich:panel>
</body> 
</html>

Page2.xhtml
<!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"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"> 

<h:head></h:head> 
<body>
    <rich:panel>
        <f:facet name="header">
        Experimenting with JSP navigation
        </f:facet>
  <h:outputText value="This is Page 2" /> 
  
 </rich:panel>
</body> 
</html>

TestBean.java
import javax.enterprise.context.RequestScoped;
import javax.faces.bean.*;

@ManagedBean(name="testbean")
@RequestScoped


public class TestBean {

 public String navigate()
 {
  return "Page2";
 }
 
 public String navigate_changeurl()
 {
  return "Page2?faces-redirect=true";
 }
}

2 comments: