且构网

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

将javascript创建的动态文本字段绑定到bean

更新时间:2022-04-30 18:22:24

与使用Javascript相比,使用后备bean可以更好地解决这一问题.使用ajax,您不需要刷新任何页面.与此类似:

You can better approach this with a backing bean than using Javascript. Using ajax you wouldn't need any page refreshes. Something along the lines of this:

HTML

<h:form>
    <p>
        <h:inputText value="#{bean.noOfFields}" />
        <h:commandButton value="Create fields">
            <f:ajax execute="@form" render="@form" />
        </h:commandButton>
    </p>

    <hr />

    <p>
        <c:forEach items=#{bean.values} varStatus="counter">
            Field no. #{counter.index} <h:inputText value="#{bean.values[counter.index}" /><br />
        </c:forEach>

        <h:commandButton action="#{bean.submit}" value="Save" />
    </p>
</h:form>

Bean.java

@ManagedBean
@ViewScoped
public class Bean {
    private String noOfFields = 1;
    private String[] values = new String[1];

    public void submit() {
        // save values in database
    }

    public String getNoOfFields() {
        return noOfFields;
    }

    public void setNoOfFields(String noOfFields) {
        try {
            values = new String[Integer.valueOf(noOfFields)];
            this.noOfFields = noOfFields;
        catch(NumberFormatException ex) {
            values = new String[1];
            noOfFields = "1";
        }
    }

    public String[] getValues() {
        return values;
    }
}

注意

如果要坚持键入事件,也可以轻松地将其绑定到<h:inputText value="#{bean.noOfFields}" />.尽管我建议不要这样做,因为每次击键都会调用另一个ajax调用.

In case you want to stick to a keyup event, you can easily bind this to <h:inputText value="#{bean.noOfFields}" /> too. Though I'd recommend not doing this, since every keystroke will invoke another ajax call.