3

I have an JSF 2.0 application that has a bean that holds a list of Strings.

I want to add the String from an <h:inputText>/> to my List and display my list.

The following code just put references in my List. So every element from my List is set to the last input.

@ManagedBean
@ApplicationScoped
public class Bean {

private String name;
private ArrayList<String> test = new ArrayList<String>();

public Bean() {
}

public Bean(String name) {
    this.name = name;
}


public String addtoList(String _name){
    test.add(_name);
    return "./index.xhtml";
} 


/***************GETTER/SETTER/HASHCODE/EQUALS**************************/
   ...

}

here a part of my index.xhtml:

        <h:inputText id="name"
                         value="#{bean.name}"
                         required="true">
        </h:inputText>
        <h:commandButton value="Post"  
                         action="#{bean.addtoList(name)}"/>  
        <br/>
        <h:dataTable var="bean"
                     value="#{bean.test}">
            <h:column>
                <h:outputText value="#{bean.name}"/>
            </h:column>

        </h:dataTable>

apllicationExample

1
  • 2
    public void addtoList(String _name){ test.add(_name); return "./index.xhtml"; } This shouldn't compile... what's your exception? Commented Nov 28, 2012 at 17:00

2 Answers 2

3

Try this:

public String addtoList() { // no parameter
    test.add(this.name); // add value of bean's property
    return "./index.xhtml";
}

and in the facelet:

<h:commandButton
    value="Post"
    action="#{bean.addtoList}"/> <!-- no parameter passed -->

The point is to have the addToList method without parameters and the string you add to the list should be the value of the name property of the backing bean.

And also, in the datatable, do not name the var the same as the backing bean. It's confusing and potentially leads to bugs. Use something like this:

<h:dataTable
    var="it"
    value="#{bean.test}">
    <h:column>
        <h:outputText value="#{it}" />
    </h:column>
</h:dataTable>
Sign up to request clarification or add additional context in comments.

2 Comments

"The point is not to add the name method parameter to the list, but the bean's name property." how should i do that?
@JavaNullPointer I edited the answer a bit. Is it still unclear to you?
0
<h:dataTable var="beany"
                         value="#{bean.test}">
                <h:column>
                    <h:outputText value="#{beany}"/>
                </h:column>

</h:dataTable>

the prob was that var="bean" is the same name of my class bean better should be another name for var

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.