tags:

views:

65

answers:

1

Say I have a JSF backing bean, request scope, that has a List as a member. In the backing bean, I have a method that is bound to a button on the page.

When the button is first pressed, the method uses an EJB to populate the list. Upon subsequent presses of the button, I do not want the method to call the DB.

So, I added a check:

if(list == null || list.size() == 0)
   //populate the list

Otherwise, the list will already be populated, so no DB call necessary. Is this satisfactory for a caching mechanism?

+1  A: 

Because the bean is request scope, its members will only exist for the lifetime of a single request. So, the data will be fetched every time a page is requested.

One thing you could do would be have the cached data in a different scope (such as session or application).

  <managed-bean>
    <managed-bean-name>expensiveBean</managed-bean-name>
    <managed-bean-class>lifetime.ExpensiveBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>
  <managed-bean>
    <managed-bean-name>requestBean</managed-bean-name>
    <managed-bean-class>lifetime.RequestBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
      <property-name>cachedAsset</property-name>
      <property-class>lifetime.ExpensiveBean</property-class>
      <value>#{expensiveBean}</value>
    </managed-property>
  </managed-bean>

Sample code:

public class RequestBean {

  private ExpensiveBean cachedAsset;

  public ExpensiveBean getCachedAsset() {
    return cachedAsset;
  }

  public void setCachedAsset(ExpensiveBean cachedAsset) {
    this.cachedAsset = cachedAsset;
  }

}

That way, you could easily reference the data from a request scope bean while keeping request-level artifacts separate.

Some frameworks add support for page scope, which keeps data tied to the lifetime of the view. That may be another option, depending on your needs.

McDowell