将<f:ajax>添加到<h:commandButton>时,未在模型中更新提交的表单值

a.u*_*u.r 3 ajax jsf form-submit jsf-2

我正在学习如何在jsf中使用ajax,我创建了一个实际上什么都没有的页面,一个填充了数字的输入文本,提交给服务器,使用提交的值调用该元素的setter,并显示getter的值.

这是简单bean的代码:

@ManagedBean(name="helper",eager=true)
public class HealthPlanHelper {


    String random = "1";

    public void setRandomize(String s){
        random = s;
                System.out.println("Calling setter");
    }

    public String getRandomize(){
        return random;
    }

}
Run Code Online (Sandbox Code Playgroud)

和jsf页面:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">
<h:head></h:head>
<h:body>

    <h:form>
        <h:commandButton action="nothing">
            <f:ajax render="num"/>
        </h:commandButton>

        <h:inputText value="#{helper.randomize}" id="num"/>
    </h:form>

</h:body>
</html>
Run Code Online (Sandbox Code Playgroud)

如你所见,这是一个请求范围的bean,每当我点击按钮时服务器显示它创建了bean的实例,但是从不调用setter方法,因此,getter总是返回"1"作为值的串.

当我删除时,正常调用setter.

Bal*_*usC 7

<f:ajax>默认情况下,进程只有当前组件(读取execute属性描述).基本上,您的代码与此完全相同:

<h:form>
    <h:commandButton action="nothing">
        <f:ajax execute="@this" render="num"/>
    </h:commandButton>
    <h:inputText value="#{helper.randomize}" id="num"/>
</h:form>
Run Code Online (Sandbox Code Playgroud)

在效果中,仅<h:commandButton action>处理了<h:inputText value>(并且任何其他输入字段,如果有的话)被完全忽略.

您需要更改execute属性以显式指定您在ajax请求期间要处理的组件或部分.通常,为了处理整个表单,@form使用了:

<h:form>
    <h:commandButton action="nothing">
        <f:ajax execute="@form" render="num"/>
    </h:commandButton>
    <h:inputText value="#{helper.randomize}" id="num"/>
</h:form>
Run Code Online (Sandbox Code Playgroud)

也可以看看: