SpringBoot
1. SpringBoot 静态资源
2. 模板引擎——Thymeleaf
Spring 官网文档: https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#using-boot-starter 找到我们对应的版本
模板引擎的作用就是我们来写一个页面模板,比如有些值是动态的,我们写一些表达式取出值,后台用model给他传过去,原来用JSP现在就用Thymelaef。
2.1 Thymeleaf 的使用
- 导入Thymeleaf Maven依赖
<!--Thymeleaf,基于3.x开发-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
- 在templates文件目录下创建.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<!--所有的html元素都可以被Thymeleaf替换接管: th:元素名-->
<div th:text="${msg}"></div>
</body>
</html>
- 在Controller层直接调用
package com.guo.springboot.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
//在templates目录下的所有页面,只能通过controller来跳转
//这个需要模板引擎的支持
@Controller
public class IndexController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","Hello Thymeleaf");
return "test";
}
}
总结:使用Thymeleaf,首先需要导入相关依赖,然后在templates目录下创建.html
2.2 Thymeleaf 的基本语法
2.2.1 读取文本
th:text="${msg}
th:utext="${msg}"
访问接口响应页面
2.2.2 遍历集合:
th:each="user :${users}"
th:text="${user}
访问接口页面响应