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

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

相关推荐
KotlinKUG贵州1 分钟前
Spring开发,从Kotlin开始
spring boot·spring·kotlin
codeRichLife21 分钟前
Mybatisplus3.5.6,用String处理数据库列为JSONB字段
java·数据库
来自星星的猫教授27 分钟前
Java 文件注释规范(便于生成项目文档)
java·注释
zhimeng330 分钟前
自己学习原理
java
程序员鱼皮34 分钟前
学 Java 还是 Go 语言?这事儿很简单!
java·后端·计算机·程序员·开发·编程经验·自学编程
Lanqing_076038 分钟前
淘宝商品详情图API接口返回参数说明
java·服务器·前端·api·电商
矮油0_o1 小时前
第一部分 -- ①语法分析的概要
java·编译器·解释器·语法分析
写bug写bug1 小时前
Dubbo中SPI机制的实现原理和优势
java·后端·dubbo
浮游本尊1 小时前
第2天Java学习作业 - 完整解答
java
一叶萩Charles1 小时前
线程与进程(java)
java·开发语言