一、引入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
二、配置application.yml
spring:
freemarker:
charset: utf-8
template-loader-path: classpath:/templates
suffix: .ftl
cache: false
server:
port: 8999
html-path: D://html
三、编写测试代码
@RestController
public class TestController {
@Value("${htmlPath}")
private String htmlPath;
@Autowired
private Configuration configuration;
@GetMapping("/html")
public String genHtml(String name,String content) {
Map<String,String> map = new HashMap<>();
map.put("title",name);
map.put("content",content);
Writer out = null;
try{
File htmlFile = new File(htmlPath + "/" + name + ".html");
if (htmlFile.exists()){
htmlFile.delete();
}
Template template = configuration.getTemplate("item.ftl");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "utf-8"));
template.process(map,out);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "ok";
}
}
四、测试
生成的文件
五、总结
页面静态化在一些大流量场景应用很多,需要学一下,各位快去学一下吧