0

My requirement is to trigger and ajax request upon the button click and show validation errors with out page refresh. Also if there is no error, navigate to second view. Below is the code im trying. Im using jsf 2.1.7 with Jboss 7.1.1 final.

<h:form>
    <h:inputText value="#{helloBean.name}"></h:inputText>
    <h:commandButton value="Welcome Me" action="#{helloBean.goToWelcome}">
    <f:ajax event="click" listener="#{helloBean.goToWelcome}"></f:ajax>
    </h:commandButton>
</h:form>


HelloBean.java

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

    public String goToWelcome(){
        System.out.println("in goToWelcome");
                return "welcome";
    }
}

I have a welcome.xhtml in the same folder as above xhtml and i can see the goToWelcome() method also being fired but the navigation does not happen. i assume its because as per the spec listener attribute should have a method with void return type and the returned string from goToWelcome() is ignored. So is there any way to achieve my requirement. Any kind of help would be highly appreciated. Thanks.

2 Answers2

0

Basically, you need to return a navigation case outcome from an action method to do navigation. Note that AJAX listener is incapable to do navigation, at least directly. If you don't want to perform navigation, you could just return null from your action method. Also, navigation won't happen if there are conversion/validation errors, as well as your action method won't be called. For this reason you need to assign a bunch of <h:message>, or a global <h:messages> to display the error messages.

To combine it, the following suffices to achieve your functionality.

The view:

<h:form>
    <h:messages id="messages">
    <h:inputText value="#{helloBean.name}" />
    <h:commandButton value="Do AJAX validation and navigate if necessary" action="#{helloBean.goToWelcome}">
        <f:ajax execute="@form" render="messages" />
    </h:commandButton>
</h:form>

The bean:

@ManagedBean
@ViewScoped
public class HelloBean implements Serializable {
    public String goToWelcome(){
        //do business job
        if(/* some condition met */) {
            return null;
        } else {
            return "nextpage";
        }
    }
}

Related reading on your topic

  1. JSF f:ajax listener vs commandButton action;
  2. How to use both Navigation Rule and f:ajax;
  3. Communication in JSF 2.0, section "Ajax validation".
Community
  • 1
  • 1
skuntsel
  • 11,624
  • 11
  • 44
  • 67
0

You probably need to redirect the page (assuming you don't have validation errors, it should work)

return "nextpage.jsf?faces-redirect=true";
Niks
  • 4,802
  • 4
  • 36
  • 55