1

I have a request scope bean with a method to retrieve some data for displaying purposes.
The method has multiple parameters so that it can get called on different occasions, also in the same view.

JSF:

<ui:repeat value="#{bean.data('foo')}"/>
<ui:repeat value="#{bean.data('bar')}"/>

Bean:

public Object[] doSomething(Object arg)
{
    Object[] data = //hit database or remote server to retrieve data;
    return data;
}

This works fine of cause, but the method is invoked multiple times for each #{bean.data(obj)} because of the jsf lifecycle phases.

I only want to hit the database once for each usage of #{bean.data(obj)}.

I tried lazy loading using following code which is not working: Now no data is displayed on my jsf page.

private Object[] data;

public Object[] doSomething(Object arg)
{
    if (this.data == null)
        this.data = //hit database or remote server to retrieve data;
    return this.data;
}

Is viewscope a to wide scope since the method is called multiple times on a view using different parameters?

4

1 回答 1

2

把它放在一个Map.

private Map<Object, Object[]> datas = new HashMap<Object, Object[]>();

public Object[] getData(Object arg) {
    Object[] data = datas.get(arg);

    if (data == null) {
        data = //hit database or remote server to retrieve data;
        datas.put(arg, data);
    }

    return data;
}
于 2012-10-07T00:41:58.117 回答