【SpringBoot】四、SpringBoot中整合Freemarker

FreeMarker 是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本( HTML 网页、电子邮件、配置文件、源代码等)的通用工具。

它不是面向最终用户的,而是一个 Java 类库,是一款程序员可以嵌入他们所开发产品的组件。
freemarker

FreeMarker 是一个很值得去学习的模版引擎。它是基于模板文件生成其他文本的通用工具。

本文主要介绍在 SpringBoot 中如何整合 FreeMarker,一起来看看吧!!!

1、引入 Freemarker 依赖

<!-- Freemarker 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- web 依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

通过 org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,我们可以看到 FreeMarker 的自动化配置,在这个类的构造方法中,注入了 FreeMarkerProperties:

@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
        public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
        public static final String DEFAULT_PREFIX = "";
        public static final String DEFAULT_SUFFIX = ".ftl";
        /**
         * Well-known FreeMarker keys which are passed to FreeMarker's Configuration.
         */
        private Map<String, String> settings = new HashMap<>();
}

FreeMarkerProperties 中则配置了 Freemarker 的基本信息,例如模板位置在 classpath:/templates/ ,再例如模板后缀为 .ftl,那么这些配置我们以后都可以在 application.yml 中进行修改。

2、在 application.yml 中进行配置 Freemarker

当然,SpingBoot 已经帮我们自动配置好了关于 Freemarker 的一系列配置,但是我们仍可以对其进行个性化配置

spring:
	freemarker:
		# 是否开启缓存
		cache: false
		# 模板文件编码
		charset: UTF-8
		# 是否检查模板位置
		check-template-location: true
		# Content-Type的值
		content-type: text/html
		# 模板文件后缀
		suffix: .ftl
		# 模板文件位置
		template-loader-path: classpath:/templates/

3、编写 Controller

@Controller
public class IndexController {

    /**
     * 请求 index 页面
     * @return
     */
     @GetMapping("index")
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView("index");
        mav.addObject("title", "首页");
        List<UserInfo> list = new ArrayList<>();
        UserInfo user = null;
        for (int i = 0; i < 10; i++) {
            user = new UserInfo();
            user.setId(i + 1);
            user.setNickName("user" + i);
            user.setSignature("SpringBoot真香,+" + (i + 1));
            list.add(user);
        }
        mav.addObject("users", list);
        return mav;
    }
}

4、创建 index.ftl 模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>${title}</title>
</head>
<body>
<table border="1">
    <tr>
        <td>用户编号</td>
        <td>用户昵称</td>
        <td>个性签名</td>
    </tr>
    <#list listas item>
    	<td>${item.id}</td>
        <td>${item.nickName}</td>
        <td>${item.signature}</td>
    </#list>
</table>
</body>
</html>

5、展示效果
首页
表格
总结

与 Thymeleaf 一样,在 SpringBoot 中对 Freemarker 做了一系列的自动化配置,真正做到了开箱即用,非常易于开发。

如您在阅读中发现不足,欢迎留言!!!

发布了100 篇原创文章 · 获赞 321 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40065776/article/details/105624642
今日推荐