纯java项目使用freemarker

引入依赖

implementation("org.freemarker:freemarker:2.3.30")
implementation("org.slf4j:slf4j-api:1.7.25")

实现

通用返回结果

package xxx;


/**
 * 通用返回结果
 * @param <T>
 */
public class CustomResult<T> {
    private static final String SUCCESS_MSG = "操作成功";
    private static final String FAILED_MSG = "操作失败";

    /**
     * 0 成功 -1 失败
     */
    private int code;
    private String msg;
    private T data;


    public CustomResult() {
    }

    public CustomResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public boolean checkSuccess(){
        return code >= 0;
    }

    public static <T> CustomResult success(){
        return success(null);
    }
    public static <T> CustomResult success(T data){
        return new CustomResult(0, SUCCESS_MSG, data);
    }



    public static <T> CustomResult fail(){
        return fail(FAILED_MSG);
    }

    public static <T> CustomResult fail(String failMsg){
        return new CustomResult(-1, failMsg, null);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

模板封装

package xxx;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;

/**
 * freemarker模板封装
 */
public class FreemarkerTemplate {
    private final static Logger logger = LoggerFactory.getLogger(FreemarkerTemplate.class);
    private final static String SLASH = "/";

    // freemarker配置
    private Configuration configuration = null;

    private FreemarkerTemplate() {
        configuration = new Configuration(Configuration.VERSION_2_3_30);
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(this.getClass(), SLASH);
    }

    //单例
    private volatile static FreemarkerTemplate instance;
    public static FreemarkerTemplate getInstance(){
        if (instance == null) {
            synchronized (FreemarkerTemplate.class) {
                if (instance == null) {
                    instance = new FreemarkerTemplate();
                }
            }
        }
        return instance;
    }

    /**
     * 输出模板字符串
     * @param dataMap
     * @param templatePath
     * @return
     */
    public CustomResult<String> generateTemplateStr(Map<String, Object> dataMap, String templatePath){
        try{
            Writer writer = new StringWriter();
            generateTemplate(dataMap, templatePath, writer);
            String content = writer.toString();
            writer.flush();
            writer.close();
            return CustomResult.success(content);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            return CustomResult.fail(e.getMessage());
        }
    }

    /**
     * 输出模板内容到文件
     * @param dataMap
     * @param templatePath
     * @param filePath
     * @return
     */
    public CustomResult<String> generateTemplateFile(Map<String, Object> dataMap, String templatePath, String filePath){
        try{
            File file = new File(filePath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            Writer writer = new FileWriter(filePath);
            generateTemplate(dataMap, templatePath, writer);
            writer.flush();
            writer.close();
            return CustomResult.success();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            return CustomResult.fail(e.getMessage());
        }
    }

    /**
     * 模板
     * @param dataMap
     * @param templatePath
     * @param writer
     * @throws IOException
     * @throws TemplateException
     */
    public void generateTemplate(Map<String, Object> dataMap, String templatePath, Writer writer) throws IOException, TemplateException {
        Template template = null;
        template = configuration.getTemplate(templatePath);
        template.process(dataMap, writer);
    }
}

测试

模板(/resources/templates/hello.ftl)

我是模板${hello}

测试类

package xxx;

import xxx.CustomResult;
import xxx.FreemarkerTemplate;

import java.util.HashMap;

public class FreemarkerTemplateTest {
    public static void main(String[] args) {
        CustomResult<String> customResult = FreemarkerTemplate.getInstance().generateTemplateStr(new HashMap(1){{
            put("hello", "hello, freemarker");
        }}, "/templates/hello.ftl");
        if(customResult.checkSuccess()){
            System.out.println(customResult.getData());
        }
    }
}

打印结果

我是模板hello, freemarker
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值