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

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

相关推荐
海梨花3 分钟前
快手面试高频算法题
java·算法·面试
云烟成雨TD11 分钟前
Spring AI 1.x 系列【37】RAG 知识库平台案例:知识库管理
java·人工智能·spring
KANGBboy14 分钟前
java知识四(面向对象编程)
android·java·开发语言
tongluowan00721 分钟前
ThreadLocal,InheritableThreadLocal,TransmittableThreadLocal详解
java·多线程·上下文
qq_2518364571 小时前
基于java Web 日化商超库存管理系统设计与实现
java·开发语言·前端
破土士V1 小时前
【Java基础语法10】继承、多态、抽象类接口、字符串与异常等
java·开发语言
轻刀快马1 小时前
撕开 Spring 的底裤:解析 Bean 生命周期与三级缓存的“破局”之术
java·spring·缓存
KobeSacre1 小时前
JVM ZGC
java·开发语言·jvm
Chase_______1 小时前
【Java基础 | 13】IO 流(下):缓冲流、转换流、序列化与综合案例
java·开发语言
itfallrain2 小时前
Spring 构造器循环依赖排查:@RequiredArgsConstructor + @Lazy 到底有没有生效
数据库·python·spring