为什么输入(例如h:inputText)嵌套在h:dataTable中不更新Bean模型? [英] Why input (for example h:inputText) nested in h:dataTable do not update Bean model?
问题描述
我有jsf页面:
....
<form jsfc="h:form" action="">
<h:dataTable value="#{newMusician.strings}" var="preferredMusicGenre" id="musicGenresSelectTable">
<h:column>
<h:inputText value="#{preferredMusicGenre}" immediate="true"/>
</h:column>
</h:dataTable>
<p>
<input type="submit" jsfc="h:commandButton" value="Add" action="#{newMusician.saveNewMusician}"/>
</p>
</form>
....
并且具有Strings的ArrayList的托管bean:
And managed bean that has ArrayList of Strings:
@ManagedBean
@ViewScoped
public class NewMusician {
private ArrayList<String> strings = new ArrayList<String>();
public NewMusician() {
strings.add("olo");
}
public ArrayList<String> getStrings() {
return strings;
}
public void saveNewMusician() {
.....
}
....
}
问题:当我更改文本并按保存按钮时,在saveNewMusician()方法中我可以看到ArrayListstrings包含相同的旧值olo,但不是输入字段中插入的值。
如果使用h:selecOneMenu,同样的问题。
Problem: When I change text in and press save button, in saveNewMusician() method I can see that ArrayList "strings" contain the same old value "olo", but not that one I inserted in input field. The same problem if use h:selecOneMenu.
如果使用不是字符串,但是将字符串和值设置为字符串的对象,情况会发生更改。
所以如果我将使用一些POJO并将inputText更改为:
Situation is changed if use not string, but object that aggregate string and set value into string. So if I'll use some POJO and change inputText to:
<h:inputText value="#{preferredMusicGenrePojo.string}" immediate="true"/>
一切都变好了。
问题:
为什么使用1级getter < h:inputText value =#{preferredMusicGenre}/>
不正确,但是使用2级别getter: code>< h:inputText value =#{preferredMusicGenrePojo.text}/> 是吗?
Question:
Why usage of 1 level getter <h:inputText value="#{preferredMusicGenre}"/>
is incorrect, but usage of 2 level getter: <h:inputText value="#{preferredMusicGenrePojo.text}"/>
is Ok?
推荐答案
String
是不可变的。它没有一个设置器的值。你需要把它包裹在一个bean(或称为POJO)中。
A String
is immutable. It doesn't have a setter for the value. You need to wrap this around in a bean (or POJO as you call it).
public class Musician {
private String preferredGenre;
// Add/generate constructor, getter, setter, etc.
}
然后更改您的托管bean如下。
Then change your managed bean as follows.
@ManagedBean
@ViewScoped
public class NewMusician {
private ArrayList<Musician> musicians = new ArrayList<Musician>();
public NewMusician() {
musicians.add(new Musician("olo"));
}
public ArrayList<Musician> getMusicians() {
return musicians;
}
public void saveNewMusician() {
// ...
}
// ...
}
您的datatable:
And your datatable:
<h:dataTable value="#{newMusician.musicians}" var="musician">
<h:column>
<h:inputText value="#{musician.preferredGenre}" />
</h:column>
</h:dataTable>
这篇关于为什么输入(例如h:inputText)嵌套在h:dataTable中不更新Bean模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!