pom

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  4. </dependency>

yum

路径后面要保留 / 否则会找不到

  1. spring:
  2. ...
  3. thymeleaf:
  4. mode: HTML
  5. encoding: UTF-8
  6. prefix: classpath:/templates/
  7. suffix: .html

创建模板

image.png

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>login</title>
  6. </head>
  7. <body>
  8. <h2 th:text="Hello + ${name}"> </h2>
  9. </body>
  10. </html>

字符串拼接优化

可以使用|围住字符串, 这样就不需要在文字后面附加’…’+’…’

<h2 th:text="|Hello ${name}|"> </h2>

Controller

@GetMapping("/login")
public String login(Model model) {
    User user = new User();
    user.setName("Jack");

    model.addAttribute("user", user);
    return "login";
}