【问题标题】:<h:inputText> doesn't seem to work within <ui:repeat>, only the last entry is submitted<h:inputText> 似乎在 <ui:repeat> 中不起作用,只提交了最后一个条目
【发布时间】:2013-06-04 04:15:58
【问题描述】:

我有一个&lt;ui:repeat&gt;&lt;ui:inputText&gt;

<ui:composition xmlns="http://www.w3.org/1999/xhtml"    
    xmlns:ui="http://java.sun.com/jsf/facelets"
    template="./templates/masterLayout.xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:c="http://java.sun.com/jsp/jstl/core">

    <ui:define name="content">
        <ui:repeat value="#{genproducts.dbList()}" var="itemsBuying">
            <div class="indproduct">
                <p class="center">#{itemsBuying.name}</p>
                <div class="center">
                    <h:form style="margin-left: auto; margin-right: auto;">
                        <h:inputText value="#{itemsBuying.amount}" />
                        <h:commandLink action="#{shoppingCart.addToCart(itemsBuying)}" value="add" />
                    </h:form>
                </div> 
            </div>
        </ui:repeat>
    </ui:define>
</ui:composition>

这是 #{genproducts} 支持 bean:

@ManagedBean(name = "genproducts")
@ViewScoped
public class Genproducts{

    public List<Product> dbList() throws SQLException {
        List<Product> list = new ArrayList<>();
        ...
        return list;
    }

} 

这是Product 实体:

@ManagedBean(name = "product")
@RequestScoped
public class Product {

    private int amount;

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

}

就我而言,dbList() 方法有四种产品。对于前三个产品,当我输入不同的值时,默认值出现在 action 方法中。仅对于最后一个产品,它按预期工作。

这是怎么引起的,我该如何解决?

【问题讨论】:

  • 使用您编写的代码,每个链接都在其自己的形式中。为什么每个链接都使用表单?将表单移出 ui:repeat:
  • 因为产品比较多,如果我把表单移到 ui:repeat 之外,就无法正常工作了。

标签: jsf arraylist user-input uirepeat


【解决方案1】:

这是因为您在 &lt;ui:repeat value&gt; 后面的 getter 方法中(重新)创建列表。这个方法在每轮迭代中被调用。因此,每次下一次迭代基本上都会破坏上一次迭代期间设置的值。在 action 方法中,您最终会得到在最后一轮迭代中创建的列表。这就是为什么最后一个条目似乎可以正常工作的原因。

这种做法确实是绝对不对的。您根本不应该在 getter 方法中执行业务逻辑。使列表成为一个属性,并且在 bean 的(后)构造期间只填充一次。

@ManagedBean(name = "genproducts")
@ViewScoped
public class Genproducts{

    private List<Product> list;

    @PostConstruct
    public void init() throws SQLException {
        list = new ArrayList<>();
        // ...
    }

    public List<Product> getList() {
        return list;
    }

} 

引用为

<ui:repeat value="#{genproducts.list}" var="itemsBuying">

另见

【讨论】:

  • 感谢 BalusC,我使用 dbList() 方法,因为它会根据用户的选择返回不同的结果。我也想知道为什么最后一个产品按预期工作,而其他产品却没有。我尝试了 p:spinner 和 h:inputText,没有任何区别。使用 ui:repeat ,我认为列表中的每个产品都应该以相同的方式工作,但事实并非如此。
  • 您应该在(post)构造函数或action(listener)方法中操作属性,而不是在属性的getter方法中。单击“另请参阅”链接以了解更多信息。至于为什么最后一个产品有效,这已经在答案的第 1 段中进行了解释。您是否也阅读了答案的文本和链接,而不仅仅是代码?
猜你喜欢
  • 2012-09-12
  • 2011-11-07
  • 2012-09-30
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多