<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在pom.xml加入thymeleaf依赖
<properties>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<!-- thymeleaf2 layout1-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
(不知道是否springboot默认的thymeleaf版本太低, 导致我运行时报错, 然后加上这个版本修改后就成功了, 如果谁知道的话请告诉我一下)
在pom.xml加入thymeleaf的版本修改
因为thymeleaf寻找页面的默认路径是templates文件夹下的html, 所以我们应该在templates文件夹下创建html.
<html lang="en" xmlns:th="http://www.thymeleaf.org">
在html页面添加语句, 作用是在编写页面时的时候有语法提示, 不添加也可以
后端
@RequestMapping("/success")
public String success(Map<String, Object> map){
User user = new User();
user.setName("abc");
logger.info("进入success...");
map.put("hello", "你好");
map.put("user", user);
map.put("array", Arrays.asList("张三", "李四", "王五"));
return "success";
}
后端 注意一下map对象是内置的,要写在方法参数中, 不能自己new 一个 map, 否则报错
前端
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>success...</h1>
<div th:text="*{hello}">这里显示欢迎信息</div>
<div th:text="*{user.name}">这里显示欢迎信息</div>
<div th:text="*{user.account}">这里显示欢迎信息</div>
<div th:text="*{user.password}">这里显示欢迎信息</div>
<h4 th:text="${user}" th:each="user : ${array}"></h4>
<div>[[${hello}]]</div> //行内显示表达
</body>
</html>
//表单
<form th:action="@{/login}" method="post">
<inpput type="sumbit" value="登录"/>
</form>
//链接
<a th:href="@{/login}">登录</a>