配置
- 如果创建项目的时候没有选择Thymeleaf模板,可以在pom.xml中添加Spring Boot专属Thymeleaf的大包依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 使用Thymeleaf代替JSP,配置原理和JSP的视图解析器一样。只是Spring Boot的已整合实现xml配置,只需要在application.properties全局资源文件配置下即可即插即用。
# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
- 基本目录
使用
- templates目录下新建一个简单的HTML文件
<!DOCTYPE html>
<!-- 引用thymeleaf的命名空间 -->
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- 语法多了个"th:",类似JSEL, ${xxx}动态加载的数据-->
<p th:text="'hello, ' + ${name}"/>
</body>
</html>
注意:text="'hello, ’ + ${name}",外用双引号,内用单引号,返过来无法识别
- 控制器
package xyz.cglzwz.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "chgl16");
return "hello";
}
}
注意:别使用@RestController,这样是返回JSON。就不能解析到视图hello.html了。
此外,每次运行crtl + z只是挂起进程,端口任然占用,切记exit。或者直接使用crtl + c强制结束。