📅  最后修改于: 2023-12-03 14:59:07.816000             🧑  作者: Mango
@ModelAttribute is a Spring MVC annotation used to bind a method parameter or a method return value to a named model attribute. It is commonly used in Spring MVC controllers to preprocess data before rendering the view or handling form submissions.
Here is an example of using @ModelAttribute
to bind method parameters:
@Controller
@RequestMapping("/products")
public class ProductController {
@ModelAttribute("categories")
public List<String> getAllCategories() {
// Retrieve list of all categories from the database
List<String> categories = productService.getAllCategories();
return categories;
}
@RequestMapping(method = RequestMethod.GET)
public String showProductForm(@ModelAttribute("product") Product product, Model model) {
// Add new product object to the model
model.addAttribute("product", new Product());
return "product/form";
}
@RequestMapping(method = RequestMethod.POST)
public String saveProduct(