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;
    }
}

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

相关推荐
AI360labs_atyun2 分钟前
Java在AI时代的演进与应用:一个务实的视角
java·开发语言·人工智能·科技·学习·ai
绿蚁新亭11 分钟前
Spring的事务控制——学习历程
数据库·学习·spring
不像程序员的程序媛1 小时前
redis的一些疑问
java·redis·mybatis
知其然亦知其所以然1 小时前
Java 面试高频题:GC 到底回收了什么、怎么回收、啥时候回收?
java·后端·面试
Z_W_H_1 小时前
【SpringBoot】 整合MyBatis+Postgresql
java·spring boot·后端
nbsaas-boot1 小时前
多租户架构下的多线程处理实践指南
java·开发语言·spring
青云交2 小时前
Java 大视界 -- Java 大数据在智能医疗远程手术机器人操作数据记录与分析中的应用(342)
java·大数据·数据记录·远程手术机器人·基层医疗·跨院协作·弱网络适配
知北游天2 小时前
Linux:多线程---同步&&生产者消费者模型
java·linux·网络
钢铁男儿2 小时前
C#接口实现详解:从理论到实践,掌握面向对象编程的核心技巧
java·前端·c#
深栈解码2 小时前
第二章:Class文件解剖:字节码的二进制密码
java·后端