SpringBoot整合Freemarker实现页面静态化的详细步骤

2022-11-13 18:11:44 整合 静态 步骤

第一步:创建项目添加依赖:

<!--WEB和actuator(图形监控用)基本上都是一起出现的-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

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

第二步:修改application.yml文件:

spring:
  freemarker:
    charset: UTF-8  #设定Template的编码
    suffix: .ftl #后缀名
    template-loader-path: classpath:/templates/  #模板加载路径,多个以逗号分隔,默认: [“classpath:/templates/”]
    cache: false  #缓存配置,是否开启template caching
    enabled: true #是否允许mvc使用freemarker

第三步:在resources/templates目录下创建模板文件index.ftl:

<html>
	<head>
		<title>${title}</title>
	</head>
	<body>
		<h2>${msg}</h2>
	</body>
</html>

第四步:创建代码静态化工具类:

@Component
public class GenUtil {

    //创建Freemarker配置实例
    @Resource
    private Configuration configuration;

    
    public void gen(String sourceFile, String aimFile, Map<String, Object> data) {
        try {
            //加载模板文件
            Template template = configuration.getTemplate(sourceFile);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(aimFile), StandardCharsets.UTF_8));
            template.process(data, out);
            out.flush();
            out.close();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

}

第五步:静态化测试

@SpringBootTest
public class GenTest {
    @Resource
    private GenUtil genUtil;
    @Test
    void fun(){
        Map<String, Object> map = new HashMap<>();
    	map.put("title", "首页");
    	map.put("msg", "好好学习,天天向上!");
    	FreemarkerUtil.execute("index.ftl", "haha.html", map);
    }
}

测试

运行测试代码发现在当前项目根目录下生成了一个haha.html的文件。

到此这篇关于SpringBoot整合Freemarker实现页面静态化的文章就介绍到这了,更多相关SpringBoot整合Freemarker内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章