如何在Thymeleaf模板中访问Spring MVC模型中的数据
时间: 2024-09-06 15:04:51 浏览: 53
在Thymeleaf模板中访问Spring MVC模型中的数据,主要通过使用Thymeleaf提供的表达式来实现。以下是一些基本的访问方式:
1. `${...}`表达式用于访问模型中的数据。这是最直接的方式,可以用来获取存储在模型对象中的数据。
例如,如果你的控制器中添加了一个名为`user`的模型属性:
```java
model.addAttribute("user", new User("张三", "zhangsan@example.com"));
```
在Thymeleaf模板中,你可以这样访问`user`对象的属性:
```html
<p>姓名:${user.name}</p>
<p>邮箱:${user.email}</p>
```
2. 使用`*{...}`表达式,它允许你从当前上下文中选择变量。当你在一个嵌套的Thymeleaf表达式中需要访问模型数据时,这种表达式特别有用。
3. 使用`#{...}`表达式来访问国际化消息。这对于在模板中显示本地化文本非常有用。
例如,如果你有一个国际化消息属性文件,你可以这样显示消息:
```html
<p th:text="#{welcome.message}">欢迎信息</p>
```
确保在使用这些表达式之前,你的项目已经正确配置了Thymeleaf和Spring MVC的支持。
阅读全文
相关推荐


















