Springboot整合Freemarker详细过程

基本配置、测试

1、导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、准备一个Freemarker模板(.ftl)
在这里插入图片描述
3、注入Configuration对象(freemarker.template包下)
在这里插入图片描述
4、生成商品详情模板

@Controller
@RequestMapping("/goodItem")
public class GoodItemController {
    @Reference
    private IGoodsService goodsService;

    @Autowired
    private Configuration configuration;

    @RequestMapping("/createHtml")
    @ResponseBody
    public String createHtml(int gid, HttpServletRequest request){
        //通过商品id获取商品详情信息
        Goods goods = goodsService.queryById(gid);
        String [] images=goods.getGimage().split("\\|");
        //通过模板生成商品静态页面
        try {
            //获取商品详情的模板对象
            Template template = configuration.getTemplate("goodsItem.ftl");
            //准备商品数据
            Map<String,Object> map=new HashMap<>();
            map.put("goods",goods);
            map.put("context",request.getContextPath());
            //freemarker页面没有分割功能,所以通过后台将图片分割后,将图片数组传到后台
            map.put("images",images);
            //生成静态页
            //获得classpath路径
            //静态页面的名称必须和商品有所关联,最简单的方式就是用商品的id作为页面的名字
            String path = this.getClass().getResource("/static/page/").getPath()+goods.getId()+".html";;
            template.process(map,new FileWriter(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
注意:
  1、freemarker页面不能通过<base th:href="${#request.getContextPath()+'/'}">获得项目的根路径。
  因此可从后台将根路径传到前端,然后通过<base href="${context}/"/>获取。
  2、当page是一个空文件夹的时候,会报错。这是因为maven项目不会对空文件夹进行打包编译。

FreeMarker的基本语法

在这里插入图片描述
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sinJack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值