springboot使用Freemark生成动态页面工具

引入pom

XML 复制代码
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

代码:

java 复制代码
import com.alibaba.fastjson.JSON;
import com.fuing.tea.commons.enums.TemplateEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.StringWriter;

/**
 * @author Garcia
 * @date 2022/8/25 14:13
 */
public class FreemarkerUtil {

    private static Configuration configuration;

    private static final String BASE_PACKAGE_PATH = File.separator + "templates";

    static Logger logger = LoggerFactory.getLogger(FreemarkerUtil.class);
    static {
        configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        // 第二步:设置模板文件所在的路径。
        configuration.setClassForTemplateLoading(FreemarkerUtil.class, BASE_PACKAGE_PATH);
        // 第三步:设置模板文件使用的字符集。一般就是utf-8.
        configuration.setDefaultEncoding("utf-8");
    }

    public static String createHtml(TemplateEnum tlf, Object model) throws Exception {
        logger.info("根据模板生成内容, 模板:{}, model={}", tlf.getName(), JSON.toJSONString(model));
        StringWriter sw = null;
        BufferedWriter writer = null;
        try {
            Template template = configuration.getTemplate(tlf.getName());
            sw = new StringWriter();
            writer = new BufferedWriter(sw);
            template.process(model, writer);
        }finally {
            if (sw!=null){
                sw.close();
            }
            if (writer!=null){
                writer.close();
            }
        }
        return sw.toString();
    }
}
java 复制代码
/**
 * @author Garcia
 * @date 2022/8/25 14:18
 */
public enum TemplateEnum {

    /**
     * 报告模板
     */
    REVIEW_REPORT("reviewTemplate.ftl","报告模板");

    private String name;

    private String desc;

    TemplateEnum(String name, String desc){
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }
}

具体怎么使用,需要自己看解析方式

相关推荐
我真的是大笨蛋5 分钟前
G1 垃圾收集器深入解析
java·jvm·笔记·缓存
ytadpole13 分钟前
揭秘 XXL-JOB 调度:从代码深处看路由策略的精妙设计
java·后端
27^×22 分钟前
Linux 常用命令速查手册:从入门到实战的高频指令整理
java·大数据·linux
学Java的bb25 分钟前
后端Web实战-Spring原理
java·spring boot·spring
float_六七33 分钟前
IntelliJ IDEA断点调试全攻略
java·ide·intellij-idea
渣哥39 分钟前
面试官最爱追问:多线程到底用来干什么?
java
七夜zippoe42 分钟前
分布式事务性能优化:从故障现场到方案落地的实战手记(一)
java·分布式·性能优化
qq_356408661 小时前
es通过分片迁移迁移解决磁盘不均匀问题
java·数据库·elasticsearch
青衫码上行1 小时前
【从0开始学习Java | 第17篇】集合(中-Set部分)
java·学习
武子康1 小时前
Java-122 深入浅出 MySQL CAP理论详解与分布式事务实践:从2PC到3PC与XA模式
java·大数据·数据库·分布式·mysql·性能优化·系统架构