Spring Boot整合 Thymeleaf
1.引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.配置文件配置
spring:
#整合thymeleaf
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
servlet:
content-type: text/html
cache: false
mode:渲染輸出模式爲HTML5
cache:不使用緩存,開發環境不要用,生產環境可以使用
3.新加入模板
<!DOCTYPE html>
<html lang="en">
<head>
<title>thyme測試</title>
</head>
<body>
<h1>Spring Boot整合 thymeleaf測試</h1>
<h2>Hello World</h2>
</body>
</html>
這個文件一定要放到 templates文件夾下,和配置文件哪裏設置的文件前綴保持一致
4.controller部分
@Controller
@RequestMapping("/thyme")
public class ThymeleafController {
@RequestMapping("/hello")
public String thyme() {
return "thyme";
}
}
注意:這裏定義了模板,所以可以使用@Controller註解。否則,會報錯。要使用@RestController註解
5.測試
啓動測試程序,輸入url,出現如下結果,說明整合成功。
url對應上述的controller部分定義的路由
代碼github地址:springboot2-demo