静态资源
SpringBoot的静态资源一般放在这四个目录下:
自定义一个首页index.html,放在前三个包下用http://localhost:8080/都能访问到
<body>
<h1>这里是首页</h1>
</body>
而在templates包下的静态资源,只能通过Controller跳转访问,还需要加上Thymeleaf模板引擎才可以
Thymeleaf模板引擎
前端交给我们的是html页面,需要转成jsp页面,可以用jsp轻松实现数据的显示,及交互等,说白了jsp即使一个模板引擎。
但是SpringBoot默认是不支持jsp的,推荐使用Thymeleaf模板引擎。
-
- 导入thymeleaf依赖
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
-
- templates包下编写test页面进行测试
-
- 编写controller后访问http://localhost:8080/t1跳转到test.html
@Controller
public class indexController {
@GetMapping("/t1")
public String index(){
return "test";
}
}
只需要把xxx.html页面放在类路径下的templates下,thymeleaf就可以帮我们自动渲染了,可与后端交互获取数据
-
- 修改测试demo,增加与后端的数据传输
@GetMapping("/t1")
public String index(Model model){
model.addAttribute("msg","这是从后端获取的数据");
return "test";
}
-
- test.html页面增加命名约束,访问http://localhost:8080/t1跳转到test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h1>This is a test!</h1>
<h2 th:text="${msg}"></h2>
</body>
</html>
语法
所有的html标签都可以用Thymeleaf替换
-
- 后端传入html标签
model.addAttribute("msg","<h1>This is a test!</h1>");
-
- test.xml中用两种方法验证
<!--不会被转义,显示原数据-->
<div th:text="${msg}"></div>
<!--会被转义,显示h1中的数据-->
<div th:utext="${msg}"></div>
each遍历
-
- 后端传入数组集合
model.addAttribute("users", Arrays.asList("Jack","Tom"));
-
- test.html中进行遍历,页面显示两个人名
<!--从user中遍历获取每个user 在text中显示-->
<h3 th:each="user:${users}" th:text="${user}"></h3> <hr>
<!--另一种写法-->
<h3 th:each="user:${users}">[[${user}]]</h3>