Spring Boot 中使用FreeMarker模板引擎

1、pom.xml 添加依赖

<!-- freemarker 模板引擎 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、编写controller

/**
 * @author sam
 * @since 2017/7/16
 */
@Controller
public class HomeController {
 
    @RequestMapping("/home")
    public String home(ModelMap modelMap) {
 
        modelMap.put("name", "Magical Sam");
 
        List<String> list = new ArrayList<>();
        list.add("sam a");
        list.add("sam b");
        list.add("sam c");
        list.add("sam d");
        modelMap.put("list", list);
 
        return "home";
    }
 
}

3、templates 下新建 home.ftl文件编写html代码,freemarker语法 可参考:FreeMarker 官方文档

home.ftl
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span>${name}</span>
    <ul>
    <#list list as item >
        <li>${item}</li>
    </#list>
    </ul>
</body>
</html>

启动应用,访问:http://localhost:8080/home ,可以得到相应结果。如需修改 freemarker 的默认配置,可以在application.properties中添加:

# ================================================
#                   FreeMarker配置
# ================================================
# 是否开启模板缓存
spring.freemarker.cache=true
# 编码格式
spring.freemarker.charset=UTF-8
# 模板的媒体类型设置
spring.freemarker.content-type=text/html
# 前缀设置 默认为 ""
spring.freemarker.prefix=
# 后缀设置 默认为 .ftl
spring.freemarker.suffix=.ftl
#spring.freemarker.allow-request-override=false
#spring.freemarker.check-template-location=true
#spring.freemarker.expose-request-attributes=false
#spring.freemarker.expose-session-attributes=false
#spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.request-context-attribute=
#spring.freemarker.template-loader-path=classpath:/templates/
#spring.freemarker.view-names=

附: application.properties 全部配置项,点击查看Spring Boot 所有配置说明


---------------------
作者:heguiliang_123
来源:CSDN
原文:https://blog.csdn.net/heguiliang_123/article/details/80518489
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/wwh/p/10097164.html