【问题标题】:How to use <h:commandButton action="#{method here}" />?如何使用 <h:commandButton action="#{method here}" />?
【发布时间】:2014-02-03 01:00:39
【问题描述】:

我愿意调用这样的方法:

<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"/>

【问题讨论】:

    标签: java jsp jsf xhtml commandbutton


    【解决方案1】:

    如果您使用的是 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

    【讨论】:

      【解决方案2】:

      该方法应具有String 返回类型,以便为适当的&lt;h:commandButton&gt; 提供正确的结果导航。它应该是这样的:

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

      这样,你应该添加两个页面,名称为:“成功”和“错误”。

      【讨论】:

        猜你喜欢
        • 2011-08-20
        • 2014-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-25
        • 1970-01-01
        • 2012-07-29
        相关资源
        最近更新 更多