spring-boot使用thymeleaf html模板并传值

在springboot中 @RestController注解相当于@ResponseBody + @Controller; 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html

使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面 若返回json等内容到页面,则需要加@ResponseBody注解

模板配置在pom.xml中配置

<!-- thymeleaf模版 -->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
com.docker.demo.controller.TestController
package com.docker.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class TestController {
          
   

    @GetMapping("test")
    public String test() {
          
   
        return "test";
    }
}
src/main/resources/templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test</title>
</head>
<body>
hello
<br>
8888
</body>
</html>
配置src/main/resources/application.yml,下面都是默认,可省略
server:
  port: 9000

spring:
  thymeleaf:
    suffix: .html
    prefix: classpath:/templates/
传值
@RequestMapping
public String test(Model model) {
          
   
    model.addAttribute("name", "dump");
    return "test";
}
<body>
hello
<br>
999
<img src="test/1.png">
<p th:text="${name}"></p>
</body>
</html>
经验分享 程序员 微信小程序 职场和发展