且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JSF 2.0中动态创建输入字段并将其链接到支持Bean

更新时间:2022-02-06 02:57:37

我假定您为地址使用了类Address.还有AddressBeanList来保持地址.

I assume that you have a class Address for the addresses. And a AddressBean with a List to keep the adresses.

代码可能看起来像这样(对于我能想到的最基本的情况):

The code might look like this (for the most basic scenario I can think of):

<h:form id="addressForm">
    <h:commandButton value="Add Address" action="#{addressBean.addAddress()}" immediate="true" execute="@this">
        <f:ajax render="addressForm" />
    </h:commandButton>
    <c:forEach items="#{addressBean.addressList}" var="address">
        <h:inputText value="#{address.street}" /><br />
    </c:forEach>
    <h:commandButton value="Save" action="#{addressBean.persistAddresses}" />
</h:form>


@ManagedBean
@ViewScoped
public class AddressBean {
    private List<Address> addressList = new ArrayList<Address>(); // getter+setter

    public void addAddress() {
        addressList.add(new Address());
    }

    public void persistAddresses() {
        // store the addressList filled with addresses
    }
}


public class Address {
    private String address; // getter+setter
}

<c:forEach>来自JSTL.它可能与<ui:repeat>一起使用,但是根据您的实际情况,可能不起作用.

<c:forEach> is taken from the JSTL. It might work with <ui:repeat>, but depending on your actual scenario it might not.