CJR
CJR

Reputation: 3572

CommandButton not working in JSF?

I have a maven/web application with JSF Framework.

This is the code for the button:

<h:form>
     <h:commandButton id="button1" value="Sign in" class="btn btn-info navbar-btn navbar-right"/> 
</h:form>

and this is from the navigation file(faces-configx.xml):

<navigation-case>
            <from-outcome>button1</from-outcome>
            <to-view-id>/pages/signin.xhtml</to-view-id>
</navigation-case>

When I click the button, it doesnt work, it doesnt take me to the signin.xhtml page. Why is that? What is wrong with my code?

Upvotes: 0

Views: 1034

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You're using Post-Redirect-Get pattern. When doing this, the JSF lifecycle, specifically in phase 5 Invoke Application, it will check that the return of the action is an empty string since you haven't defined an output from the action attribute in your <h:commandButton>:

<h:commandButton id="button1" value="Sign in" action="" />
                                              ^-------^
                                              not written, JSF assumes this

JSF will search this outcome in faces-config.xml and fire the navigation rule, if exists.

With this in mind, you have 3 alternatives:

  1. Set the outcome to a valid navitagion rule:

    <navigation-rule>
        <from-view-id>*</from-view-id>
        <navigation-case>
            <from-outcome>signin</from-outcome>
            <to-view-id>logout.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    

    And in Facelets:

    <h:commandButton value="Sign in" action="signin" />
    
  2. Create a proper managed bean which has a method that returns a String that matches with the proper navigation case:

    @ManagedBean
    @RequestScoped
    public class FooBean {
        public String signin() {
            return "signin";
        }
    }
    

    And in Facelets:

    <h:commandButton value="Sign in" action="#{fooBean.signin}" />
    
  3. A more proper solution for this case: don't use Post-Redirect-Get pattern, instead use direct navigation (Redirect-Get) through <h:button> (no form required).

    <h:button value="Sign in" outcome="signin" />
    

    Code above assumes signin.xhtml file exists in the same path of the file where this code is placed. This is:

    - webapp <-- root folder of the web pages of the app
      - another_folder <-- some folder
      + file.xhtml <-- file that contains <h:button>
      + signin.xhtml <-- file to navigate
    

Upvotes: 3

Vitor Santos
Vitor Santos

Reputation: 611

I believe you're not using the commandButton correctly.

I think this question can help you:

Difference between h:button and h:commandButton

Upvotes: -1

Related Questions