First try of Thymeleaf template engine

Although the template engine cannot decouple the code from the view, it is suitable for individual developers. If there are front-end and back-end projects, the template engine will undoubtedly have advantages when the front-end requests a large number of back-end projects.

SpringBoot integration steps:

  1. Introduce dependencies
  2. Write yml configuration
  3. Write html template files
  4. Write the Controller interface
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
spring:
  thymeleaf:
    enabled: true  #开启thymeleaf视图解析
    encoding: utf-8  #编码
    prefix: classpath:/templates/  #前缀
    cache: false  #是否使用缓存
    mode: HTML  #严格的HTML语法模式
    suffix: .html  #后缀名
<!DOCTYPE html>
<!--标记 thymeleaf 语法-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
  
<body>
<h1> Hello <span th:text="${username}"></span>
</h1>
</body>
</html>
// 此处使用 @Controller注解 与 ModelAndView 进行视图选择、传参
@Controller
public class User {
    
    
    @GetMapping("user")
    ModelAndView get() {
    
    
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("user");		// 视图选择
        modelAndView.addObject("username", "小明");		// 传参
        return modelAndView;
    }
}

Guess you like

Origin blog.csdn.net/qq_35760825/article/details/128986086