SpringBoot通过freemarker模板,返回字符串或生成文件

  • Post author:
  • Post category:其他

目的:通过一个模板文件,数据填充后以字符串返回,或者生成一个文件

pom文件:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
    <version>2.4.2</version>
</dependency>

yml文件:

spring:
  freemarker:
    charset: UTF-8 # 编码
    template-loader-path: classpath:/ttp # 模板路径

模板ftl文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
	name: ${name}
</body>
</html>

使用方法:

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    
    public String test() throws IOException, TemplateException {
        // 配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        
        // 获取模板
        Template template = configuration.getTemplate("demo.ftl");
        
        // 数据
        Map<String, Object> dataModel  =new HashMap<>();
        dataModel.put("name", "大老师");
        
        // 创建输出对象
        // 输出成文件
        FileWriter resultFile = new FileWriter("E:/1.html");
        // 输出为字符串
        StringWriter resultStr = new StringWriter();
        
        // 渲染模板
        template.process(dataModel, resultStr);
        template.process(dataModel, resultFile);
		// 关闭流
        resultStr.close();
        resultFile.close();
        
        System.out.println(resultStr);
        return resultStr.toString();
    }

版权声明:本文为qq704200551原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。