1、引入依赖
主要增加spring-boot-starter-thymeleaf和nekohtml这两个依赖。
spring-boot-starter-thymeleaf:Thymeleaf自动配置
nekohtml:允许使用非严格的html语法,一般我们在使用html5的时候,就会要求严格遵守w3c标准,就是在单标签的后面”/“结束符,否则不会渲染页面。所以我们使用非严格的html,以跳过严格的检查
2、在application.yml中配置Thymeleaf
spring:
thymeleaf:
cache: false # 开发时关闭缓存,否则无法看到实时页面
mode: html5 # 用非严格的html
encoding: utf-8
servlet:
content-type: text/html
3、修改html文件标签用于thymeleaf引擎,这样才可以在其他标签里使用th:*语法,声明如下:
index.html(Thymeleaf文件以.html为后缀)
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span th:text="${user.username}">张明</span>
</body>
</html>
4、pom文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
</dependencies>
5、Controller层
@Controller //注意此处不能写为@RestController,否则返回的是json字符串,而不是字符串,项目找不到静态页面
public class UserController {
@RequestMapping("/test")
public String test(Model model){
User user = new User();
user.setUsername("小红");
model.addAttribute("user",user);
return "index";
}
}
6、springboot集成themeleaf报Namespace 'th' is not bound
这种问题可能是模板引擎文件中没有配置
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
7、探讨Model和ModelAndView的区别
Model是每次请求中都存在的默认参数,利用其addAttribute()方法即可将服务器的值传递到jsp页面/模板引擎页面中;
ModelAndView包含model和view两部分,使用时需要自己实例化,利用ModelMap用来传值,也可以设置view的名称
@Controller
public class UserController {
@RequestMapping("/test")
public String test(Model model){
User user = new User();
user.setUsername("小红");
model.addAttribute("user",user);
return "index";
}
@RequestMapping("/testModelAndView")
public ModelAndView test1(){
User user = new User();
user.setUsername("小明");
ModelAndView modelAndView = new ModelAndView();
//将数据放置到ModelAndView对象view中,第二个参数可以是任何java类型
modelAndView.addObject("user",user);
// 利用约定大于配置的规则,自动的去resources/templates找index.html
// 设置跳转地址
modelAndView.setViewName("index");
return modelAndView;
}
}