pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.6</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>
application.yml
server: port: 8080 spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8
IndexController
@Controller @RequestMapping("/index") public class IndexController { @GetMapping("/index") public String index(){ System.out.println("首页"); return "index"; } }
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello Thymeleaf</h1> </body> </html>
结果
数据传递
去index时,添加了一个User集合,怎么获取呢
@Controller @RequestMapping("/index") public class IndexController { @GetMapping("/index") public String index(Model model){ System.out.println("首页"); List<User> users = new ArrayList<>(); users.add(new User(1,"小刘",12)); users.add(new User(2,"张三",23)); users.add(new User(3,"王五",10)); model.addAttribute("users",users); return "index"; } }
index.html
<!DOCTYPE html> <html xmlns:th = "http://www.thymeleaf.org"></html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello Thymeleaf</h1> <table> <tr> <th>id</th> <th>name</th> <th>age</th> </tr> <tr th:each="user:${users}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> <td th:text="${user.age}"></td> </tr> </table> </body> </html>
注意:如果你的资源希望通过地址栏直接进行访问,那么,你可以新建一个 static 包,这是 spring boot 专门放静态资源的,约定大于配置,否则必须通过 controller 控制器映射才可以访问静态资源
thymeleaf下
static下