modelandview.addobject
时间: 2023-03-16 14:50:42 浏览: 252
ModelAndView.addObject() 方法是 Spring MVC 框架中用于向视图添加模型数据的方法。它接受两个参数:一个是模型属性的名称,另一个是模型属性的值。添加的数据可以在 JSP 页面中使用 EL 表达式访问。
相关问题
modelandview.addobject()
In Spring MVC, the `ModelAndView` class is used to pass data between the controller and the view. The `addObject()` method is used to add an object to the model, which can then be accessed by the view.
The `addObject()` method takes two parameters: a `String` key and an `Object` value. The key is used to identify the object in the model, and the value is the object that is added to the model.
For example, suppose we have a controller method that retrieves a list of products and adds it to the model:
```
@RequestMapping("/products")
public ModelAndView getProducts() {
List<Product> products = productService.getAllProducts();
ModelAndView modelAndView = new ModelAndView("products");
modelAndView.addObject("products", products);
return modelAndView;
}
```
In this example, we create a new `ModelAndView` object with the view name "products". We then add the list of products to the model using the key "products". This means that in the view, we can access the list of products using the key "products":
```
<c:forEach var="product" items="${products}">
<tr>
<td>${product.name}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
```
Here, we use the `c:forEach` tag from the JSTL to loop through the list of products and display their names and prices in a table. We access the list of products using the key "products", which was added to the model in the controller method.
@RequestMapping("/student") public class StudentController { @Autowired private StudentServie studentServie; @Autowired private DormitoryService dormitoryService; @GetMapping("/list") public ModelAndView list(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("studentmanager"); modelAndView.addObject("list", this.studentServie.list()); modelAndView.addObject("dormitoryList", this.dormitoryService.availableList()); return modelAndView; }
这段代码是一个基于Spring MVC框架的Java Web应用程序的控制器类,用于处理与学生信息相关的HTTP请求。其中,@RequestMapping注解指定了该控制器处理的请求URL路径为"/student",list()方法则处理该路径下的"/list"子路径的GET请求。
在该控制器中,使用了@Autowired注解自动注入了两个依赖:StudentServie和DormitoryService,这两个服务类分别用于处理学生和宿舍信息的业务逻辑。
list()方法返回了一个ModelAndView对象,该对象包含了两个属性:list和dormitoryList,分别对应了学生列表和可用宿舍列表的数据模型。最后,该方法将视图名称设置为"studentmanager",表示响应该请求时将返回名为"studentmanager"的视图页面。
阅读全文