java - 如何使用<h :commandButton action ="#{method here}"/>?

标签 java jsp jsf xhtml commandbutton

我愿意调用这样的方法:

<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?

o:validateEqual

关于java - 如何使用<h :commandButton action ="#{method here}"/>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21122516/

相关文章:

java - 如何用通用方法找出最小值?

Java JTextPane HTML 编辑器 UTF-8 字符编码

java - 在 Eclipse 中运行 spring MVC 应用程序时出现 HTTP-404 错误 - Tutorials point hello world example

css - 如何在JSP上打印账单

javascript - OnMouseOver 子菜单在 Firefox 中不显示

java - JSF commandButton 操作返回正确的值,但导航规则不适用

html - 样式化 JSF ICEFaces ace :dialog

jsf - jsf 的日期+时间选择器

java - 用于可选

java - 如何使用 Spring SimpleThreadScope?