freemarker获取html模板进行渲染输出

freemarker获取html模板进行渲染输出

应用场景

1、获取html文件内容进行模板解析,返回到页面展示
2、获取html文件内容进行模板解析,进行邮件发送
3、获取xml文件内容进行模板接卸

maven工程配置引入依赖

    org.freemarker
    freemarker
    2.3.28


创建获取模板

  1. 注解
    //Freemaker的核心配置类,用于动态生成模板对象
    //在SpringBoot IOC容器初始化的时候,自动Configuration就被实例化
    @Resource
    private Configuration freemarkerConfig;
  1. 代码
  //获取模板对象
        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 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";
    }

生成静态文件

freemarker获取html模板进行渲染输出_第1张图片
image.png

你可能感兴趣的:(freemarker获取html模板进行渲染输出)