model.addAttribute 前端接受
时间: 2024-04-30 20:23:17 浏览: 7
在Spring MVC中,model.addAttribute()方法用于将数据传递到前端页面。在前端页面中,可以通过Thymeleaf、JSP等模板引擎语言,使用EL表达式获取传递的数据。例如:
在Controller中:
```
@GetMapping("/user")
public String getUser(Model model) {
User user = userService.getUserById(1L);
model.addAttribute("user", user);
return "user";
}
```
在user.html页面中:
```
<div th:text="${user.name}"></div>
<div th:text="${user.age}"></div>
```
这样就可以将Controller中获取到的User对象传递到前端页面,并在页面中展示用户的姓名和年龄。
相关问题
model.addattribute前端接收
在前端,可以使用JavaScript接收并获取model.addattribute传递的数据。例如:
```
let data = document.getElementById("elementId").getAttribute("attributeName");
```
其中,"elementId"是HTML元素的id,"attributeName"是model.addattribute设置的属性名称。
model.addattribute在前端怎么获取数据
在Spring MVC中,使用`model.addAttribute`将数据添加到模型中,可以在前端通过`${}`语法来获取数据。
举个例子,在后端Controller中添加数据:
```
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("name", "World");
return "hello";
}
```
在前端页面中,可以使用`${}`语法获取数据:
```
<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
</body>
</html>
```
在页面加载时,`${name}`会被解析为后端传递的数据,从而渲染成`Hello, World!`。
当然,前提是你需要在前端使用模板引擎来解析这些数据,比如使用Thymeleaf、Freemarker等。