目的:通过一个模板文件,数据填充后以字符串返回,或者生成一个文件
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();}