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

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

相关推荐
侠客行031711 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪11 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚13 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎13 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
Yvonne爱编码14 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚14 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂14 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang14 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
琹箐14 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
__WanG14 小时前
JavaTuples 库分析
java