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

4
我正在学习如何在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;
    }

}

还有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>

如您所见,这是一个请求范围的bean,每当我点击按钮时,服务器都会显示它创建了一个bean实例,但setter方法从未被调用,因此getter方法始终返回字符串值"1"。

当我去掉<h:outputText>标签时,setter方法正常调用。

1个回答

8
< p > <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>

实际上,只有<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>

另请参阅:


那个运行正常,这是否意味着同样的事情也适用于验证器(不仅是setter,而是与执行组件相关联的任何过程)? - a.u.r
1
没错。它会影响从恢复视图到呈现响应的所有阶段(获取请求参数、转换、验证、更新模型和调用操作)。使用 execute,您基本上可以控制在表单提交期间应处理哪些组件。请注意,在例如 PrimeFaces 中,这已经默认为 @form(并且他们将 execute 重命名为 process(并将 render 重命名为 update),这在我看来更有意义)。 - BalusC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接