广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot整合Freemarker实现页面静态化的详细步骤
  • 166
分享到

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

SpringBoot整合Freemarker页面静态化SpringBoot整合Freemarker 2022-11-13 18:11:44 166人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

第一步:创建项目添加依赖: <!--WEB和actuator(图形监控用)基本上都是一起出现的--> <dependency> <groupId

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

<!--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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot整合Freemarker实现页面静态化的详细步骤

本文链接: https://www.lsjlt.com/news/170146.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作