环境搭建
- 创建springboot项目时勾选
web
和thymeleaf
依赖 - 在
templates
目录下新建test.html
文件<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>test</h1> </body> </html>
- 在
SpringbootWebApplication
同级目创建TestController
由于springboot默认的有编码和前后缀我们可以不用自己设置@Controller public class TestController { @GetMapping("test") public String hello(){ return "test"; } }
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
- 启动项目访问
http://localhost:8080/test
,正常跳转
使用thymeleaf接收数据
th:text 和 th:utext
修改controller
@Controller
public class TestController {
@GetMapping("test")
public String hello(Model model){
model.addAttribute("msg", "hello,springboot");
return "test";
}
}
修改html
<!DOCTYPE html>
<!--导入约束-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--使用th:元素名 进行绑定 变量表达式:${...}-->
<!--text会进行转义 utext不会进行转义-->
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
</body>
</html>
页面显示
th:each
controller中添加数据
model.addAttribute("users", Arrays.asList("starry","xiaohei"));
html
<p th:each="user:${users}" th:text="${user}"></p>
页面显示