Springboot动态加载FreeMarker网页模板

Springboot动态加载FreeMarker网页模板

一、依赖引入

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

二、配置文件

spring:
  mvc:
    static-path-pattern: /static/**

三、创建index.ftl

在resources/static/下创建index.ftl模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
${test}
</body>
</html>

四、创建TestController.java

package com.example.demo.controller;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.MediaType;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <b><code>TestController</code></b><br>
 * <b>Description:</b> TODO <br>
 * <b>Creation Time:</b> 2022/8/12 19:20 <br><br>
 *
 * @author soul
 * @version demo1 v1.0
 */
@RestController
public class TestController {
    @GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE)
    public String index() throws IOException, TemplateException {
        String htmlText = "";
        Configuration configuration = new Configuration();
        // 打jar包时去掉“/classes”,在jar同级目录下拷贝static文件夹
        configuration.setDirectoryForTemplateLoading(
        new File(new ApplicationHome(getClass()).getSource().getParentFile().toString()
                + "/classes" + "/static"));
        Template template = configuration.getTemplate("index.ftl", "UTF-8");
        template.setEncoding("UTF-8");
        Map<String,Object> params = new HashMap<>();
        params.put("test", "测试");
        htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, params);
        return htmlText;
    }
}

五、效果展示

添加target/classes/static/index.ftl模板后(打包后直接添加模板至static目录内即可)

成功访问界面
移除target/classes/static/index.ftl模板后(打包后直接移除模板至static目录内即可)

移除模板后失败界面

六、jar打包注意

打jar包时去掉“/classes”,在jar同级目录下拷贝static文件夹

打包注意



附录:FreeMarker官方手册

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ssoul、肥鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值