Thymeleaf 是一个现代化的、服务端的Java模板引擎。
1、新建Spring项目:demo7,增加依赖:Spring Web、Spring Configuration Processor、Lombok、Thymeleaf 。自动生成的pom.xml如下。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、 ThymeleafAutoConfiguration
1)@EnableConfigurationProperties(ThymeleafProperties.class),Thymeleaf的所有配置值都在ThymeleafProperties
里。
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
默认前缀是类路径下的templates目录,默认后缀是.html。
2)SpringResourceTemplateResolver defaultTemplateResolver(),配置模板解析器。
3)SpringTemplateEngine templateEngine(),配置模板引擎。
4)ThymeleafViewResolver thymeleafViewResolver(),配置视图解析器。
3、com.example.boot下新建控制器:controller.ViewController。
package com.example.boot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ViewController {
@GetMapping("/success")
public String index(Model model){
model.addAttribute("message","Hello,Thymeleaf");
return "success";
}
}
4、resources.templates下新建视图:index.html和success.html。
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<a href="/success">success</a>
</body>
</html>
<!-- success.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
5、启动应用,点击链接,访问接口:localhost:8080/success。