【问题标题】:Submitted form values not updated in model when adding <f:ajax> to <h:commandButton>将 <f:ajax> 添加到 <h:commandButton> 时未在模型中更新提交的表单值
【发布时间】:2013-07-31 10:05:46
【问题描述】:

我正在学习如何在 jsf 中使用 ajax,我创建了一个实际上什么都不做的页面,一个用数字填充的输入文本,提交到服务器,使用提交的值调用该元素的设置器,然后显示 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”作为字符串的值。

当我删除 setter 时,会正常调用。

【问题讨论】:

    标签: ajax jsf jsf-2 form-submit


    【解决方案1】:

    &lt;f:ajax&gt; 默认只处理当前组件 (read description of execute attribute)。基本上,您的代码与此完全相同:

    <h:form>
        <h:commandButton action="nothing">
            <f:ajax execute="@this" render="num"/>
        </h:commandButton>
        <h:inputText value="#{helper.randomize}" id="num"/>
    </h:form>
    

    实际上,只有&lt;h:commandButton action&gt; 被处理,&lt;h:inputText value&gt;(以及任何其他输入字段,如果有的话)被完全忽略。

    您需要更改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,还包括与执行组件相关的任何进程)?
    • 没错。它影响恢复视图和呈现响应之间的所有阶段(获取请求参数、转换它、验证它、更新模型和调用操作)。使用execute,您基本上可以控制在表单提交期间应该处理哪些组件。请注意,例如PrimeFaces 这已经默认为 @form (他们将 execute 重命名为 process(并将 render 重命名为 update),这使得 IMO 更有意义)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2021-10-26
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多