thymeleaf如何访问model中的String数据
时间: 2023-06-06 21:06:42 浏览: 73
Thymeleaf 通过表达式语言访问 model 中的 String 数据,语法为“${variableName}”,其中 variableName 是在 model 中定义的名称。例如,如果在 model 中定义了一个名为“name”的 String 变量,则可以使用表达式“${name}”来访问它。
相关问题
thymeleaf的model
Thymeleaf的Model是在使用Thymeleaf模板引擎时,用于向模板中传递数据的对象。它是一个键值对的集合,可以通过键值对的方式将数据存储到Model中,然后在模板中使用这些数据进行动态渲染。
在Java中,使用Thymeleaf时,我们可以通过创建一个Model对象来传递数据到模板中。可以在Controller方法中创建一个Model对象,并使用其addAttribute()方法来添加数据。例如:
```java
@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "hello-template"; // 返回模板名称
}
}
```
在上面的示例中,我们通过调用model.addAttribute()方法将名为"message"的键和对应的值"Hello, Thymeleaf!"存储到Model中。在模板中,可以使用Thymeleaf的表达式语言`${message}`来访问并显示这个值。
Thymeleaf的Model使得我们能够将动态数据传递给模板,从而实现动态生成网页内容。
thymeleaf model数据共享
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.