首先导入依赖:
- <dependencies>
- <!--web--> <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!--thymeleaf模板-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- <!--test-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
默认配置:
不需要做任何配置,启动器已经把Thymeleaf的视图配置完成:
默认前缀:classpath:/templates
默认后缀:.html
所以如果需要返回视图:user,会指向到classpath:/templates/user.html
页面缓存:
Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致修改的页面不会立即被展现,需要重启才可以,因此需要关闭缓存:
- # 关闭Thymeleaf的缓存
- spring.thymeleaf.cache=false
另外,在idea中,修改完毕页面,需要使用快捷键:ctrl+shift+F9来刷新工程(即刷新修改过的页面)
快速开始:
新建一个controller,控制视图跳转:
- package com.leyou.page.web;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.GetMapping;
- @Controller
- public class HelloController {
- @GetMapping("hello")
- public String toHello() {
- return "hello";// 普通字符串被当成视图名称,结果前缀和后缀查找视图
- }
- }
新建一个html模板:
- <!DOCTYPE html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>Hello</title>
- </head>
- <body>
- <h1>
- msg:<span th:text="${msg}"></span>
- </h1>
- </body>
- </html>
注意!!!需要把html的命名空间,加上:
- xmlns:th="http://www.thymeleaf.org"
否则不会有语法提示。