JSF "cache" some preloaded variables

340 Views Asked by At

I have a Page which fills on every "preRenderView" some lists with values of a DB

//preRenderView Method
public void init(){
    loadChapterStructure();
    loadCategoryStructure();
}    

Due to the fact, that the chapters and categories don't chance really often (e.g. just one time a day), they only should be loaded once for every user (on first page load).

When the user now performs some GET-requests on the same view (to keep the page etc. bookmarkable), it would be good not to load these "static" values again.

Is there a way to achieve e.g. loading the chapters and categories e.g. only once every hour? Is there any best-practice for this issue?

Thanks for any help!

1

There are 1 best solutions below

0
On

You can implement an @ApplicationScoped managed bean which caches the DB values. Just access the data through it instead of directly using the DAO from your view beans:

@ManagedBean
@ApplicationScoped
public class CacheManager(){

    private static Date lastChapterAccess;

    private static Date lastCategoryAccess;

    private List<Chapter> cachedChapters; 

    private List<Category> cachedCategories; 

    private Dao dao;

    //Refresh the list if the last DB access happened 
    //to occur more than one hour before
    public List<Chapter> loadChapterStructure(){
        if (lastChapterAccess==null || new Date().getTime() 
            - lastChapterAccess.getTime() > 3600000){
            cachedChapters = dao.loadChapterStructure();
            lastChapterAccess = new Date();
        }
        return cachedChapters;
    }

    public List<Category> loadCategoryStructure(){
        if (lastCategoryAccess==null || new Date().getTime() 
            - lastCategoryAccess.getTime() > 3600000){
            cachedCategories = dao.loadCategoryStructure();
            lastCategoryAccess = new Date();
        }
        return cachedCategories;
    }


}

Then inject the bean wherever your want using the @ManagedProperty annotation:

@ManagedBean
@ViewScoped
public class ViewBean{

    @ManagedProperty(value="#{cacheManager}")
    private CacheManager cacheManager;

    //preRenderView Method
    public void init(){
        chapters = cacheManager.loadChapterStructure();
        categories = cacheManager.loadCategoryStructure();
    }    

}