JSF-2 f:带有Map的selectItems不显示itemLabel

Ale*_*ond 16 jsf el map jsf-2

当我使用f:selectItems来显示Map中的项目时,我无法显示Map项的值,只显示键.f:selectItems根本不使用itemLabel.当我使用List而不是工作.

以下确实使用itemLabel来显示List中项目的"描述":

<h:selectOneMenu>
  <f:selectItems value="#{testBB.testList}" var="s"
    itemLabel="TEST #{s.description}" itemValue="#{TEST s.name}" />
</h:
selectOneMenu>
Run Code Online (Sandbox Code Playgroud)

以下尝试在Map中显示项目的值不起作用.它显示项目的键,但不使用itemLabel属性,因为可以通过缺少"TEST"文本的输出来识别.

<rich:select>
  <f:selectItems value="#{testBB.testMap}" var="s"
    itemLabel="TEST #{s.value}" itemValue="TEST #{s.key}" />
</rich:select>
Run Code Online (Sandbox Code Playgroud)

使用的简单支持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;
  }

}
Run Code Online (Sandbox Code Playgroud)

那么,关于如何使这项工作的任何想法,即如何有效地使用带有selectItems的Map?

Bal*_*usC 42

你的问题很合理,但是代码让人感到困惑和含糊.我会在这个答案中忽略你的代码.

至于具体的问题,"如何使用Map<f:selectItems>",你需要认识到,地图功能键为默认被用作商品标签和映射值默认被用作项目值.你似乎期望它是相反的方式(老实说,我直觉也期望,但这只是一个设计决定 - 地图键强制唯一性和选项标签应该在UI视角绝对是唯一的,但选项值不一定非常独特).

所以,这应该做(注意我LinkedHashMap在这里使用,因为它维护插入顺序):

map = new LinkedHashMap<String, String>();
map.put("Label 1", "value1");
map.put("Label 2", "value2");
map.put("Label 3", "value3");
Run Code Online (Sandbox Code Playgroud)

<f:selectItems value="#{bean.map}" />
Run Code Online (Sandbox Code Playgroud)

如果你想交换键和值,那么你应该迭代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");
Run Code Online (Sandbox Code Playgroud)

<f:selectItems value="#{bean.map.entrySet()}" var="entry" 
    itemValue="#{entry.key}" itemLabel="#{entry.value}" />
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • @jack:如果您使用的是&lt;f:selectItem&gt;而不是&lt;f:selectItems&gt;,则会发生这种情况。注意复数。 (2认同)