modelandview.addobject()
时间: 2024-05-02 16:18:15 浏览: 85
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.
阅读全文