1、环境配置

(1)引入thymeleaf

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

(2)自动配置

@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration

配置好的信息

  • 配置的属性都在 ThymeleafProperties中
  • 配置好了SpringResourceTemplateResolver资源模板解析器
  • 配置好了SpringTemplateEngine模板引擎
  • 默认模板存放在

      public static final String DEFAULT_PREFIX = "classpath:/templates/";
    
      public static final String DEFAULT_SUFFIX = ".html";
    

(3)开发示例

  • 添加路由请求地址

      @GetMapping("/haha")
      public String haha(Model model){
          model.addAttribute("link","https://www.daijunyi.com");
          return "haha";
      }
    
  • 创建html页面 haha.html存放在templates下

    <!DOCTYPE html>
    <html lang="en" xmlns:th="https://www.thymeleaf.org">
    <head>
      <meta charset="UTF-8">
      <title>Title</title>
    </head>
    <body>
      <a href="www.baidu.com" th:href="${link}">百度知道</a>
    </body>
    </html>
    

    (4)示例2 登录页

      @GetMapping("/login")
      public String loginPage(){
          return "login";
      }
    
      @PostMapping("/login")
      public String loginPost(User user, HttpSession session, Model model){
          if (StringUtils.hasText(user.getUsername()) && "123456".equals(user.getPassword())){
              session.setAttribute("user",user);
              return "redirect:/index.html";
          }else{
              model.addAttribute("msg","账号密码错误");
              return "login";
          }
      }
    
      @GetMapping("/index.html")
      public String indexPage(HttpSession session,Model model){
          if (session.getAttribute("user") != null){
              return "index";
          }else{
              model.addAttribute("msg","请重新登录");
              return "login";
          }
      }