thymeleaf 使用示例
**********************
示例
**************
pojo 层
Person
@Data
public class Person {
private Integer id;
private String name;
private Integer age;
}
**************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public ModelAndView hello(ModelAndView mv){
Person person=new Person();
person.setId(1);
person.setName("瓜田李下");
person.setAge(20);
mv.addObject("person",person);
List<Person> list=new ArrayList<>();
for (int i=0;i<5;i++){
Person p=new Person();
p.setId(i);
p.setName("海贼王 "+i);
p.setAge(20+i);
list.add(p);
}
mv.addObject("list",list);
mv.setViewName("hello");
return mv;
}
}
**************
前端页面
hello.html
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:align="center" th:if="${person} != null" style="color: greenyellow">
<span th:text="${person.getId()}"></span> ==>
<span th:text="${person.getName()}"></span> ==>
<span th:text="${person.getAge()}"></span>
</div><br>
<div th:align="center" th:if="not ${#lists.isEmpty(list)}" style="color: orange">
<div th:each="person:${list}">
<span th:text="${person.getId()}"></span> ==>
<span th:text="${person.getName()}"></span> ==>
<span th:text="${person.getAge()}"></span>
</div>
</div>
</body>
</html>
**********************
使用测试
localhost:8080/hello