thymeleaf model数据共享
时间: 2023-07-14 19:06:28 浏览: 81
thymeleaf回显数据
5星 · 资源好评率100%
Thymeleaf provides a way to share data between the controller and the view using the model object. The model object is essentially a map that allows you to store data and pass it to the view. Here's how you can share data using Thymeleaf:
1. In your controller, create a model object and add data to it:
```java
@GetMapping("/example")
public String example(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "example";
}
```
2. In your Thymeleaf template, access the data using Thymeleaf expressions:
```html
<p th:text="${message}"></p>
```
In this example, the value of the "message" attribute in the model is displayed in the paragraph tag.
You can also use the model object to share more complex data objects or collections. For example:
```java
@GetMapping("/users")
public String getUsers(Model model) {
List<User> users = userService.getAllUsers();
model.addAttribute("users", users);
return "users";
}
```
In the Thymeleaf template, you can then iterate over the "users" list:
```html
<table>
<tr th:each="user : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
</tr>
</table>
```
By using the model object, you can easily share data between the controller and the view in Thymeleaf.
阅读全文