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”作为细绳。

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

4

1 回答 1

8

默认情况下<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>

也可以看看:

于 2013-07-31T03:14:05.583 回答