Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
871 views
in Technique[技术] by (71.8m points)

jsf - How map multiple inputText to an array property?

I want the user to enter one or more names to the JSF's inputText components. So I'm thinking of a managed bean like this:

public class MyBean {

    private String[] names;

    public String[] getNames() {
        return names;
    }

    public void setNames(String[] names) {
        this.names = names;
    }
}

But, how do I map the JSF's inputText components to this array property?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, you need to preserve the array in bean's (post)constructor. E.g.

public MyBean() {
    names = new String[3];
}

Then, you can either just access them by an hardcoded index

<h:inputText value="#{myBean.names[0]}" />
<h:inputText value="#{myBean.names[1]}" />
<h:inputText value="#{myBean.names[2]}" />

or use <ui:repeat> with a varStatus to access them by a dynamic index

<ui:repeat value="#{myBean.names}" varStatus="loop">
    <h:inputText value="#{myBean.names[loop.index]}" />
</ui:repeat>

Do not use the var attribute like

<ui:repeat value="#{myBean.names}" var="name">
    <h:inputText value="#{name}" />
</ui:repeat>

It won't work when you submit the form, because String doesn't have a setter for the value (the getter is basically the toString() method).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...