当我使用 f:selectItems 在 Map 中显示项目时,我无法显示 Map 项目的值,只能显示键。 f:selectItems 根本不使用 itemLabel。当我使用 List 代替时,一切正常。
以下确实使用 itemLabel 来显示列表中项目的“描述”:
<h:selectOneMenu>
<f:selectItems value="#{testBB.testList}" var="s"
itemLabel="TEST #{s.description}" itemValue="#{TEST s.name}" />
</h:
selectOneMenu>
以下尝试在 Map 中显示项目的值不起作用。它显示项目的键,但不使用 itemLabel 属性,这可以通过缺少“TEST”文本的输出来识别。
<rich:select>
<f:selectItems value="#{testBB.testMap}" var="s"
itemLabel="TEST #{s.value}" itemValue="TEST #{s.key}" />
</rich:select>
使用的简单支持 bean 如下:
public class TestBB {
private Map<String, String> testMap;
private List<TestItem> testList;
public TestBB() {
testMap = new HashMap<String, String>();
testMap.put("1_key", "Item One");
testMap.put("2_key", "Item Two");
testMap.put("3_key", "Item Three");
testList = new ArrayList<TestItem>();
testList.add( new TestItem("name_1", "description_1") );
testList.add( new TestItem("name_2", "description_2") );
testList.add( new TestItem("name_3", "description_3") );
}
public Map<String, String> getTestMap() {
return testMap;
}
public List<TestItem> getTestList() {
return testList;
}
}
那么,关于如何使其工作的任何想法,即如何有效地使用带有 selectItems 的 Map?
最佳答案
您的问题是合理的,但代码使它令人困惑和模棱两可。我将在此答案中忽略您的代码。
至于具体问题“如何在 Map
中使用 <f:selectItems>
”,您需要意识到默认情况下使用映射键作为项目标签,并且默认使用映射值作为项目值。您似乎希望它是相反的(老实说,我直觉上也希望如此,但这只是一个设计决定 - map 键强制唯一性和选项标签在 UI 角度肯定应该是唯一的,但选项值不一定需要是唯一的)。
所以,应该这样做(注意我在这里使用 LinkedHashMap
,因为它维护了插入顺序):
map = new LinkedHashMap<String, String>();
map.put("Label 1", "value1");
map.put("Label 2", "value2");
map.put("Label 3", "value3");
和
<f:selectItems value="#{bean.map}" />
如果你想交换键和值,那么你应该迭代
Map#entrySet()
.这仅在您的环境支持 EL 2.2 时有效,因为您必须通过直接方法调用来调用它,因为没有 getter。例如。
map = new LinkedHashMap<String, String>();
map.put("value1", "Label 1");
map.put("value2", "Label 2");
map.put("value3", "Label 3");
和
<f:selectItems value="#{bean.map.entrySet()}" var="entry"
itemValue="#{entry.key}" itemLabel="#{entry.value}" />
也可以看看:
selectOneMenu
wiki page 关于JSF-2 f :selectItems with Map does not display itemLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10655349/