Thymeleaf
Thymeleaf
快速开始
在
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
另外,在
<html xmlns:th="http://www.thymeleaf.org">
因为
spring:
thymeleaf:
cache: false #关闭缓存
否则会有缓存,导致页面没法及时看到更新后的效果。比如你修改了一个文件,已经
访问静态页面
这个和
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
这是404页面
</body>
</html>
我们再写一个
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {
@RequestMapping("/test404")
public String test404() {
return "index";
}
@RequestMapping("/test500")
public String test500() {
int i = 1 / 0;
return "index";
}
}
当我们在浏览器中输入
Thymeleaf 中处理对象
我们来看一下
public class Blogger {
private Long id;
private String name;
private String pass;
// 省去set和get
}
然后在
@GetMapping("/getBlogger")
public String getBlogger(Model model) {
Blogger blogger = new Blogger(1L, "xxx", "123456");
model.addAttribute("blogger", blogger);
return "blogger";
}
我们先初始化一个
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>博主信息</title>
</head>
<body>
<form action="" th:object="${blogger}">
用户编号:<input name="id" th:value="${blogger.id}" /><br />
用户姓名:<input
type="text"
name="username"
th:value="${blogger.getName()}"
/><br />
登陆密码:<input type="text" name="password" th:value="*{pass}" />
</form>
</body>
</html>
</html>
可以看出,在
- 使用
th:value="*{属性名}"
- 使用
th:value="${ 对象. 属性名}" ,对象指的是上面使用th:object 获取的对象 - 使用
th:value="${ 对象.get 方法}" ,对象指的是上面使用th:object 获取的对象
Thymeleaf 中处理List
处理
@GetMapping("/getList")
public String getList(Model model) {
Blogger blogger1 = new Blogger(1L, "xxx", "123456");
Blogger blogger2 = new Blogger(2L, "达人课", "123456");
List<Blogger> list = new ArrayList<>();
list.add(blogger1);
list.add(blogger2);
model.addAttribute("list", list);
return "list";
}
接下来我们写一个
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>博主信息</title>
</head>
<body>
<form action="" th:each="blogger : ${list}" >
用户编号:<input name="id" th:value="${blogger.id}"/><br>
用户姓名:<input type="text" name="password" th:value="${blogger.name}"/><br>
登录密码:<input type="text" name="username" th:value="${blogger.getPass()}"/>
</form>
</body>
</html>
可以看出,其实和处理单个对象信息差不多,th:each
进行遍历,${}
取${对象.属性名}
来获取${对象.get方法}
来获取,这点和上面处理对象信息是一样的,但是不能使用 *{属性名}
来获取对象中的属性,