编写目标:通过springboot加上Thymeleaf模板在网页上输出相关字句:用户:Tom

1:引入起步依赖

主要核心代码为:

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
  </parent>

  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
     <version>2.1.6.RELEASE</version>
   </dependency>

2:编写启动类

@SpringBootApplication
public class SpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }
}

3:编写控制器类

@Controller
public class Controller {
    @RequestMapping("/welcome")
    public ModelAndView welcome() {
        ModelAndView modelAndView = new ModelAndView("hello");
        modelAndView.getModel().put("name", "Tom");
        return modelAndView;
    }
}

4:在application.properties里,编写thymeleaf模板参数

spring.thymeleaf.enabled=true

spring.thymeleaf.content-type=text/html

spring.thymeleaf.check-template-location=true

spring.thymeleaf.cache=false

spring.thymeleaf.prefix=classpath:/templates/

spring.thymeleaf.suffix=.html

5:编写包含thymeleaf模板的hello.html页面


<!DOCTYPE html>
<html  lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>welcome</title>
</head>
<body>
用户:<span th:text="${name}"></span>
</body>
</html>

错误总结:

写完代码后,发现无论怎么改都显示输出结果有错误,然后一个个类查找,发现是起步依赖的问题, <parent>写成了3xx版本,而Thymeleaf依赖是2xx版本,导致不兼容,对这个问题才多加了解和注意,改回一致2.1.6.RELEASE版本后,结果输出正确。


阳元升
1 声望0 粉丝