模版引擎虽然不能够实现代码与视图解耦,但是其适合于个人开发者使用,而且如果存在前后端项目中,前端大量请求后端时,模版引擎无疑也存在优势。
SpringBoot 整合步骤:
- 引入依赖
- 编写 yml 配置
- 编写 html 模版文件
- 编写 Controller 接口
<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 进行视图选择、传参@Controllerpublic class User { @GetMapping("user") ModelAndView get() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("user"); // 视图选择 modelAndView.addObject("username", "小明"); // 传参 return modelAndView; }}