天天看點

巧用Freemarker的自定義方法

要想使用Freemarker支援的自定義方法,需要實作freemarker.template.TemplateMethodModel接口,然後将方法對象放入到Freemarker的資料模型中,這樣在ftl檔案中便可以像使用Freemarker内置方法一樣使用該方法了。 

import java.util.List;  
import javax.servlet.http.HttpServletResponse;  
import freemarker.template.TemplateMethodModel;  
import freemarker.template.TemplateModelException;  
  
/** 
 * Freemarker自定義方法 
 * 實作response.encodeURL(url)功能 
 */  
public class EncodeURLMethod implements TemplateMethodModel {  
      
    private HttpServletResponse response;  
      
    /** 
     * 帶參數的構造函數 
     * @param response HttpServletResponse對象 
     */  
    public EncodeURLMethod(HttpServletResponse response)  
    {  
        this.response=response;  
    }  
  
    /** 
     * 執行方法 
     * @param argList 方法參數清單 
     * @return Object 方法傳回值 
     * @throws TemplateModelException 
     */  
    public Object exec(List argList) throws TemplateModelException {  
        if(argList.size()!=1)   //限定方法中必須且隻能傳遞一個參數  
        {  
            throw new TemplateModelException("Wrong arguments!");  
        }  
        //傳回response.encodeURL執行結果  
        return response.encodeURL((String)argList.get(0));  
    }  
}      

輸出模版資料模型時,将EncodeURLMethod的執行個體對象放入模型中:

dataMap.put("encodeURL", new EncodeURLMethod(context.getResponse()));      

在Freemarker模版檔案中這樣使用:

${encodeURL("/news/showNews.sf?id=123456")}