springboot中themyleaf传递数据
时间: 2023-07-03 13:22:46 浏览: 52
在 Spring Boot 中使用 Thymeleaf 传递数据有两种方式,分别是:
1. 使用 Model 对象传递数据
在 Controller 方法中,通过 Model 对象将数据传递给视图。例如:
```java
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "World");
return "hello";
}
```
在上述例子中,将字符串 "World" 存储在名为 "name" 的模型属性中,并将模板名称 "hello" 返回给 Spring MVC,用于渲染视图。
在 Thymeleaf 视图中,可以通过 `${name}` 表达式获取传递的数据。例如:
```html
<h1>Hello, <span th:text="${name}"></span>!</h1>
```
在上述例子中,通过 `${name}` 表达式获取传递的数据,在页面中显示 "Hello, World!"。
2. 使用 @ModelAttribute 注解传递数据
在 Controller 方法中,使用 @ModelAttribute 注解将数据绑定到方法参数上。例如:
```java
@GetMapping("/hello")
public String hello(@ModelAttribute("name") String name) {
return "hello";
}
```
在上述例子中,使用 @ModelAttribute 注解将字符串 "World" 绑定到名为 "name" 的方法参数上,并将模板名称 "hello" 返回给 Spring MVC,用于渲染视图。
在 Thymeleaf 视图中,可以通过 `${name}` 表达式获取传递的数据。例如:
```html
<h1>Hello, <span th:text="${name}"></span>!</h1>
```
在上述例子中,通过 `${name}` 表达式获取传递的数据,在页面中显示 "Hello, World!"。
以上是使用 Thymeleaf 传递数据的两种方式,可以根据具体情况选择合适的方式进行传递数据。