JSF-2 f :selectItems with Map does not display itemLabel

标签 jsf jsf-2 map el

当我使用 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}" />

也可以看看:
  • Our selectOneMenu wiki page
  • 关于JSF-2 f :selectItems with Map does not display itemLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10655349/

    相关文章:

    jsf-2 - 通过js禁用按钮

    Scala 和 Map 值

    java - Primefaces 向导。如何返回onnext的js函数选项卡

    java - 为什么不对 JSF 页面进行预编译(至少部分),而是在每次构建 View 时对其进行解析和评估?

    tomcat - javax.servlet.ServletException - 我怎样才能找到原因?

    jsf - 从应用程序范围的 Bean 中释放 Cdi 注入(inject)的对象

    jsf - 如何使用 <p :media>? 绑定(bind)动态内容

    python - 如何在 Python 中使用 "map"函数? (如何重写 for 循环?)

    matlab - MATLAB 中的映射有多少字节?

    java - JSF : Elements of ArrayList are not rendered properly?