码迷,mamicode.com
首页 > 其他好文 > 详细

巧用Freemarker的自定义方法

时间:2014-08-15 12:31:08      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   使用   io   文件   

要想使用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输出的结果。

巧用Freemarker的自定义方法,布布扣,bubuko.com

巧用Freemarker的自定义方法

标签:style   blog   http   color   java   使用   io   文件   

原文地址:http://www.cnblogs.com/eastson/p/3914485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!