170703、springboot编程之模板使用(thymeleaf、freemarker)

官方不推荐集成jsp,关于使用jsp模板我这里就不赘述,如果有需要的,请自行百度!

thymeleaf的使用

1、在pom中增加thymeleaf支持

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

注:Thymeleaf默认是有缓存的,当然不是我们需要的,在配置文件中可以关闭缓存

2、application.properties配置

####thymeleaf模板使用
##关闭thymeleaf缓存
spring.thymeleaf.cache=false

3、编写模板文件helloHtml.html

首先在resources文件下创建templates,然后在templates创建helloHtml.html文件

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello World!</h1>
<p th:text="${hello}"></p>
</body>
</html>

4、编写TemplateController.java控制器类

package com.rick.apps.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * Desc :  模板测试
 * User : RICK
 * Time : 2017/8/22 13:33
  */
@Controller
public class TemplateController {
    /**
     * 返回html模板.
     */
    @RequestMapping("/helloHtml")
    public String helloHtml(Map<String,Object> map){
        map.put("hello","Hello Spring Boot");
        return"/helloHtml";
    }
}

5、启动项目,访问http://localhost:8080/helloHtml

使用freemarker

1、在pom中增加freemarker支持

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

2、编写TemplateController.java控制器类

 /**
     * 返回freemarker html模板.
     */
    @RequestMapping("/helloFtl")
    public String helloFtl(Map<String,Object> map){
        map.put("hello","Hello freemarker");
        return"/helloFtl";
    }

3、创建helloFtl.ftl

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>${hello}</p>
</body>
</html>

4、启动访问http://localhost:8080/helloFtl

另外需要注意的是:thymeleaf和freemarker是可以同时存在的!

项目清单:

原文地址:https://www.cnblogs.com/zrbfree/p/7411213.html