interceptor和ognlvaluestack

只是自己的想法,不對不要扔雞蛋哦。

今天突發奇想的實現一個小小的cache。把分類categories放入map中,cache起來。
    private void cache() {
        
if(log.isDebugEnabled()){
            log.debug(
"Starting cache the categoriesdot.gif");
        }
        cacheCategoryMap 
= new HashMap();
        cacheCategoryMap.put(
"categories",categoryDao.getCategories());
    }

然後我想在interceptor裏面把categories寫到ognlvaluestack裏面這樣我在ftl裏面就可以<#list categories>....</#list>了。因爲這個是在每個頁面的header.ftl裏面的。我也就不需要再每個action裏面去get一下了。
剛開始我implements Interceptor

        final OgnlValueStack stack = ActionContext.getContext().getValueStack();
        stack.setValue(
"categories" ,categoryManager.getCategories());
        
return invocation.invoke();
可是這樣也不可以。後來我想到是不是action執行完畢之後就把stack中的這個值清空了我又用了。AroundInterceptor 我想在after裏面去設置不就可以了。
    protected void after(ActionInvocation dispatcher, String result) throws Exception {
        
final OgnlValueStack stack = ActionContext.getContext().getValueStack();
        stack.setValue(
"categories" ,categoryManager.getCategories());
    }
可是這樣還是不可以。我暈了。我想是不是要在action裏面聲明一下categories。
    private List categories;

    
public List getCategories() {
        
return categories;
    }


    
public void setCategories(List categories) {
        
this.categories = categories;
    }

然後在before裏面去get就可以了。
    protected void before(ActionInvocation invocation) throws Exception {
        
final OgnlValueStack stack = ActionContext.getContext().getValueStack();
        stack.setValue(
"categories" ,categoryManager.getCategories());
    }

總算實現了。不過還要在每個action裏面聲明一下categories,這樣還是很不好的。剛纔有人建議用filter。我在試試吧.


http://leaf.jdk.cn/index.php/archives/91
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章