How to display elements of ArrayList by index in E

2019-02-17 16:57发布

问题:

I want to display java arraylist into JSF page. I generated arraylist from database. Now I want to display the list into JSF page by calling the list elements index by index number. Is it possible to pass a parameter to bean method from an EL expression in JSF page directly and display it?

回答1:

You can access a list element by a specific index using the brace notation [].

@ManagedBean
@RequestScoped
public class Bean {

    private List<String> list;

    @PostConstruct
    public void init() {
        list = Arrays.asList("one", "two", "three");
    }

    public List<String> getList() {
        return list;
    }

}
#{bean.list[0]}
<br />
#{bean.list[1]}
<br />
#{bean.list[2]}

As to parameter passing, surely it's possible. EL 2.2 (or JBoss EL when you're still on EL 2.1) supports calling bean methods with arguments.

#{bean.doSomething(foo, bar)}

See also:

  • Our EL wiki page
  • Invoke direct methods or methods with arguments / variables / parameters in EL

I however wonder if it isn't easier to just use a component which iterates over all elements of the list, such as <ui:repeat> or <h:dataTable>, so that you don't need to know the size beforehand nor to get every individual item by index. E.g.

<ui:repeat value="#{bean.list}" var="item">
    #{item}<br/>
</ui:repeat>

or

<h:dataTable value="#{bean.list}" var="item">
    <h:column>#{item}</h:column>
</h:dataTable>

See also:

  • How iterate over List<T> and render each item in JSF Facelets


标签: jsf arraylist el