2014-01-14 32 views
1

我願意稱這樣的方法:如何使用<h:commandButton action =「#{method here}」/>?

<h:commandButton value="Register" action="#{account.action}"/> 

有了這樣的後續類:

package com.sources; 

public class Account { 
    private String password1; 
    private String password2; 

    public String getPassword1() { 
     return password1; 
    } 

    public void setPassword1(final String password1) { 
     this.password1 = password1; 
    } 

    public String getPassword2() { 
     return password2; 
    } 

    public void setPassword2(final String password2) { 
     this.password2 = password2; 
    } 

    public void action() { 
     //if the passwords matchs 
      //change page 
     //else 
      //display an error on the xhtml page 
    } 
} 

在該方法中,我想改變頁面或顯示錯誤,這取決於關於註冊的有效性。

改變頁面將是一樣的跟隨動作,但堪稱方法#{account.action}

<h:commandButton value="Register" action="connect"/> 

回答

3

如果您使用JSF-2,你可以使用隱式導航:

public String action() { 
    if (password1 != null && password2 != null && password1.equals(password2)) { 
     return "connect"; 
    } else { 
     FacesMessage msg = new FacesMessage("Passwords do not match"); 
     FacesContext.getCurrentInstance().addMessage(null, msg); 
     return null; 
    } 
} 

這將導航到頁面connect.xhtml如果兩個密碼相同。如果不是,註冊頁面將被重新渲染。要顯示消息,您需要將

<h:form> 
    <h:messages globalOnly="true" /> 
    <h:inputText value="#{account.password1}" /> 
    <h:inputText value="#{account.password2}" /> 
    <h:commandButton value="Register" action="#{account.action()}" /> 
</h:form> 

添加到您的頁面。

參見:

Creating FacesMessage in action method outside JSF conversion/validation mechanism?

o:validateEqual

1

的方法應該有String返回類型,以提供正確的結果導航到相應的<h:commandButton>。它應該看起來像這樣:

public String action() { 
    if (/* condition here */) { 
     return "success"; 
    } 
    else // condition is wrong 
     return "error"; 
} 

這樣,您應該添加2個名爲「success」和「error」的頁面。

相關問題