freemarker 自定义标签

1.编写标签类

package com.pccw.business.fnd.common.filegen;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class FinalReport2Directive implements TemplateDirectiveModel {

    /**
     * @param env
     *            上下文变量
     * @param params
     *            标签参数
     * @param loopVars
     * @param body
     *            标签体
     */
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        TemplateModel prjojectNumTM = (TemplateModel)params.get("projectNum");
        System.out.println(prjojectNumTM.toString());
        
        body.render(new FinalReportCustomWriter(env.getOut()));
        
    }

    private static class FinalReportCustomWriter extends Writer {

        private final Writer out;

        FinalReportCustomWriter(Writer out) {
            this.out = out;
        }

        public void write(char[] cbuf, int off, int len) throws IOException {
            
            StringBuffer buf = new StringBuffer();
            buf.append("<tr><td>11</td></tr>");
            for (int i = 0; i < 50; i++) {
                buf = new StringBuffer();
                buf.append("<tr><td>" + i + "orderName" + "</td></tr>");
                buf.append("<tr><td>" + i + "orderNum" + "</td></tr>");
                buf.append("<tr><td>" + i + "orderQuantity" + "</td></tr>");
                buf.append("<tr><td>" + i + "orderPrice" + "</td></tr>");
                out.write(buf.toString());
            }
        }

        public void flush() throws IOException {
            out.flush();
        }

        public void close() throws IOException {
            out.close();
        }
    }
}

2.  编写文件生成类,单例

package com.pccw.business.fnd.common.filegen;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class HtmlFileBuild {
    
    
    private static HtmlFileBuild htmlFileBuild = null;
    private Configuration configuration;

    private  HtmlFileBuild(){
        configuration =  new Configuration();
    }
    
    public static HtmlFileBuild getInsance(){
        if(htmlFileBuild == null){
            htmlFileBuild  = new HtmlFileBuild();
        }
        return htmlFileBuild;
    }

    /**
     * 
     * @param context
     *            上下文
     * @param data
     *            绑定数据
     * @param templateFileName
     *            模板名称
     * @param targetHtmlFileName
     *            生成目标文件名称
     * @return 生成html文件路径
     * @throws Exception
     */
    public String crateHTML(ServletContext context, Map<String, Object> data, String templateFileName,
            String targetHtmlFileName) throws Exception {

        try {
            // 模板存放路径
            this.configuration.setDirectoryForTemplateLoading(new File(
                    "D:/projects/FAS/trunk/dev/arch/WebRoot/business/template"));

            // 模板文件名称
            Template template = this.configuration.getTemplate(templateFileName);
            template.setEncoding("UTF-8");
            // 静态页面要存放的路径
            String htmlPath = targetHtmlFileName;
            File htmlFile = new File(htmlPath);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
            // 处理模版 map数据 ,输出流
            data.put("projectNum", "B00002");
            template.process(data, out);
            out.flush();
            out.close();
            return targetHtmlFileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    // test
    public static void main(String arg[]) throws Exception {
        new HtmlFileBuild().crateHTML(null, new HashMap(), "finalReport2.ftl", "E:/tmp/freemarker/finalReport2.html");
    }
}

3. finalReport2.ftl

<#assign fr2 = "com.pccw.business.fnd.common.filegen.FinalReport2Directive"?new()>
<table style="border:1px">
<@fr2  projectNum="${projectNum}">

</@fr2>
</table>
原文地址:https://www.cnblogs.com/rigid/p/4304768.html