[英]JSF: Adding a String to List
I have an JSF 2.0 application that has a bean that holds a list of Strings.我有一个 JSF 2.0 应用程序,它有一个包含字符串列表的 bean。
I want to add the String from an <h:inputText>/>
to my List and display my list.我想将
<h:inputText>/>
的字符串添加到我的列表并显示我的列表。
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:这是我的 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>
Try this:尝试这个:
public String addtoList() { // no parameter
test.add(this.name); // add value of bean's property
return "./index.xhtml";
}
and in the facelet:并在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.关键是让
addToList
方法不带参数,您添加到列表中的字符串应该是支持 bean 的name
属性的值。
And also, in the datatable, do not name the var
the same as the backing bean.而且,在数据表中,不要将
var
命名为与支持 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>
<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
问题是
var="bean"
是我的类bean
的同名更好应该是var
另一个名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.