2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > SpringBoot通过freemarker模板 返回字符串或生成文件

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

时间:2022-12-10 03:44:48

相关推荐

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

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

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>

使用方法:

@Autowiredprivate 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();}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。