Freemarker自定义指令功能应用

    /**
     * 之前用freemarker,在前端页面处理时候总觉得它的字符串截取功能不强,但是一直没有多费时间解决。
     * 最近有点儿时间,总算优化了下它,靠的,还是freemarker的自定义指令功能。
     * 需求:页面上给出了一个固定宽度的位置(如30px),然后将不定长的字符串填充满这个区域(字符串由字母、数字、符号和汉字组成)     *
     * 多余的字符串必须给予截掉,不管是字母,还是汉字,都必须将此区域最大限度的填满
     *
     * 问题:如采常规方式,采用ftl写一个macro或者function,然后截取指定长度的字符串,遇到字母与汉字混合,就肯定会有问题,因为一个汉字宽度是一个字母宽度的两倍,依据其中任何一个来计算,都会有问题
     *
     * 为此,专门写了个函数 Substr
     * 功能:指定长度截取等宽字符串, 解决汉字与字母混合情况下的字
     *
     * 第一,写个类:Substr
     * 第二,在系统启动的时候进行注册包含有此函数的类

     * 第三,在.ftl文件中应用,就像使用freemarker的内置函数一样方便
     *
 */

//  下面是主要的清单:

//  第一步

import java.util.List;

import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

public class Substr implements TemplateMethodModel {

 

    // 这里的长度计算,以汉字为标准,两个字母作为一个字符
    public Object exec(List args) throws TemplateModelException {
        if(args.size()!=2)
            throw new TemplateModelException("Wrong arguments!");
       
        int length=2*Integer.parseInt(args.get(1).toString(),10);
        char[] arraySource=String.valueOf(args.get(0)).toCharArray();
       
        StringBuffer result=new StringBuffer("");       
        for(char c:arraySource){
            int ASCIICode=(int)c;
            if(ASCIICode<=255){
                length-=1;
            }else{
                length-=2;
            }
            result.append(c);
            if(length==0)break;
        }
        return new SimpleScalar(result.toString());       
    }   
}

 

// 第二步:

// 先写了个简单的servlet小试下,

public class HelloServlet extends HttpServlet {
    private Configuration cfg;    
    public void init() {       
        cfg = new Configuration();    

 

        // 告诉servlet你的ftl文件存放目录   
        cfg.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/templates");     
    }
   
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {  
        Map root = new HashMap();
     
        Template t = cfg.getTemplate("test.ftl"); // 给定测试用的ftl文件
      
        resp.setContentType("text/html; charset=" + t.getEncoding());
        Writer out = resp.getWriter();       
        try { 
            // 在比较单一的环境下,可以直接这样使用          
            root.put("substr",new Substr());
            t.process(root, out);           
            out.flush();
        } catch (TemplateException e) {
            throw new ServletException(
                    "Error while processing FreeMarker template", e);
        }
    }
}

 

 

// 第三步应用,ftl文件就不贴了,主要有两句

<#assign aboutname="some周三123thing456"/>

 ${substr(aboutname,4)}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章