freemarker获取html模板进行渲染输出
应用场景
1、获取html文件内容进行模板解析,返回到页面展示
2、获取html文件内容进行模板解析,进行邮件发送
3、获取xml文件内容进行模板接卸
maven工程配置引入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
创建获取模板
- 注解
//Freemaker的核心配置类,用于动态生成模板对象
//在SpringBoot IOC容器初始化的时候,自动Configuration就被实例化
@Resource
private Configuration freemarkerConfig;
- 代码
//获取模板对象
Template template = freemarkerConfig.getTemplate("goods.ftl");
Map param = new HashMap();
param.put("goods", goodsService.getGoods(gid));
param.put("covers", goodsService.findCovers(gid));
param.put("details", goodsService.findDetails(gid));
param.put("params", goodsService.findParams(gid));
File targetFile = new File("d:/babytun/goods/" + gid + ".html");
FileWriter out = new FileWriter(targetFile);
template.process(param , out);
out.close();
return targetFile.getPath();
完整代码
@GetMapping("/static/{gid}")
@ResponseBody
public String doStatic(@PathVariable("gid") Long gid) throws IOException, TemplateException {
//获取模板对象
Template template = freemarkerConfig.getTemplate("goods.ftl");
Map param = new HashMap();
param.put("goods", goodsService.getGoods(gid));
param.put("covers", goodsService.findCovers(gid));
param.put("details", goodsService.findDetails(gid));
param.put("params", goodsService.findParams(gid));
File targetFile = new File("d:/babytun/goods/" + gid + ".html");
FileWriter out = new FileWriter(targetFile);
template.process(param , out);
out.close();
return targetFile.getPath();
}
@GetMapping("/static_all")
@ResponseBody
public String doStatic() throws IOException, TemplateException {
//获取模板对象
Template template = freemarkerConfig.getTemplate("goods.ftl");
List<Goods> allGoods = goodsService.findAllGoods();
for (Goods g : allGoods) {
Long gid = g.getGoodsId();
Map param = new HashMap();
param.put("goods", goodsService.getGoods(gid));
param.put("covers", goodsService.findCovers(gid));
param.put("details", goodsService.findDetails(gid));
param.put("params", goodsService.findParams(gid));
File targetFile = new File("d:/babytun/goods/" + gid + ".html");
FileWriter out = new FileWriter(targetFile);
template.process(param , out);
out.close();
}
return "ok";
}
生成静态文件
![](https://img.haomeiwen.com/i4994935/35b2b744c0d1b889.png)
网友评论