我愿意调用这样的方法:
<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"/>
最佳答案
如果您使用 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?
关于java - 如何使用<h :commandButton action ="#{method here}"/>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21122516/