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文件夹