导航

巧用Freemarker的自定义方法

Posted on 2014-08-15 11:43  eastson  阅读(409)  评论(0编辑  收藏  举报

要想使用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")}  

输出结果实际就是使用response.encodeURL输出的结果。