如何获取jsf f所选项目的索引:selectItems?

时间:2014-05-05 20:53:40

标签: jsf jsf-2 selectoneradio

我有seleconeradio,例如:

<h:selectOneRadio value="#{myBean.selectedValue}" layout="pageDirection">
    <f:selectItems value="#{myBean.myList}" var="a" itemValue="#{a}" itemLabel="#{a}"/>
</h:selectOneRadio>

其中myList是整数列表,例如1,3,2,4。 如果用户在myBean selectedValue中选择第二个元素(即3),那么我想得到selectItems项的索引。

我应该在f:selectItems itemValue标签中写什么?或者这是不可能的?

P.S。我可以通过创建一个新类来实现它,在该类中我有index属性并创建该类的新列表,给出正确的索引。但这是非常糟糕的解决方案。

2 个答案:

答案 0 :(得分:5)

在这种情况下,您实际上可以使用c:forEach。当您必须处理包含重复项的集合时,这尤其有用,因此无法使用indexOf()

<h:selectOneRadio value="#{myBean.selectedValue}" layout="pageDirection">
  <c:forEach items="#{myBean.myList}" var="a" varStatus="idx">
    <f:selectItem itemValue="#{idx.index}" itemLabel="#{a}"/>
  </c:forEach>
</h:selectOneRadio>

如果还没有完成,请确保包含JSP JSTL Core命名空间。

xmlns:c="http://xmlns.jcp.org/jsp/jstl/core

答案 1 :(得分:0)

你应该使用 indexOf(Object o) ..它返回此列表中第一次出现的指定元素的索引,如果此列表不包含该元素,则返回-1 ... 你的代码应该看起来像这样......

int index  = myList.indexof(selectedValue);