玩转 SpringBoot 2 快速整合 | FreeMarker篇

时间:2019-09-17
本文章向大家介绍玩转 SpringBoot 2 快速整合 | FreeMarker篇,主要包括玩转 SpringBoot 2 快速整合 | FreeMarker篇使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

FreeMarker 介绍

Apache FreeMarker™是一个模板引擎:一个Java库,用于根据模板和更改数据生成文本输出(HTML网页,电子邮件,配置文件,源代码等)。模板是用FreeMarker模板语言(FTL)编写的,这是一种简单的专用语言(不像PHP这样的完整编程语言)。通常,使用通用编程语言(如Java)来准备数据(发布数据库查询,进行业务计算)。然后,Apache FreeMarker使用模板显示准备好的数据。在模板中,您将专注于如何呈现数据,而在模板之外,您将关注于要呈现的数据。

SpringBoot 官方比较推荐使用 Thymeleaf,由于自己对 FreeMarker 相对比较熟悉,所以这里我先介绍一下如何在 SpringBoot 中使用 FreeMarker 当前前端页面使用。
                                                                                  ——以上内容摘抄自 FreeMarker 官网   

SpringBoot 使用 FreeMarker 操作步骤

第一步是在pom.xml 中引入 spring-boot-starter-freemarker 依赖具体代码如下:

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

第二步是在resources 下 templates 创建test目录新建 freemarkDemo.ftl 内容如下:

<h1>${msg}</h1>

 第三步是创建访问 freemarkDemo.ftl 的Controller。


@Controller
@RequestMapping("/hello")
public class HelloWorldController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg", "SpringBoot With Freemark hello world!");
        return "test/helloworld";
    }
}

测试

在游览器输入访问 FreeMarker 页面的 Controller 的 URL:http://localhost:8080/sbe/hello/test   进行测试,测试结果如下:

小结

SpringBoot 使用 FreeMarker 步骤如下:

  1. 添加 FreeMarker starter依赖
  2. 创建模版页面和访模版问页面Controller

代码示例

具体代码示例请查看我的 GitHub 仓库 springbootexamples 中模块工程名: spring-boot-2.x-freemarker 下进行查看。

GitHub:https://github.com/zhuoqianmingyue/springbootexamples

原文地址:https://www.cnblogs.com/jerry126/p/11531305.html