Spring MVC Annotations @ModelAttribute

I have a question about Spring MVC annotations @ModelAttribute. In the first method called "addProduct", I create a model of the model and after calling model.addAttribute I can use the name "product" in the jsp file, for example product.getProductPrice. But in the second method, which is called the first, I added the parameter "@ModelAttribute (" product ") Product product", but why? If I delete this annotation, my program will work the same as before, please explain to me) Thank you so much, sorry for my English, I'm from Ukraine)

@RequestMapping("/admin/productInventory/addProduct")
public String addProduct(Model model) {
    Product product = new Product();
    // add default for radio button!
    product.setProductCategory("Mobile Phone");
    product.setProductCondition("New");
    product.setProductStatus("active");

    model.addAttribute("product", product);

    return "addProduct";
}

@RequestMapping(value = "/admin/productInventory/addProduct", method = RequestMethod.POST)
public String addProduct(@ModelAttribute("product") Product product, HttpServletRequest request) {
    productDao.addProduct(product);

    MultipartFile productImage = product.getProductImage();
    String rootDirectory = request.getSession().getServletContext().getRealPath("/");
    System.out.println(rootDirectory);
    // product id as the file name
    // !!!! TODO
    // path = Paths.get(rootDirectory + "/WEB-INF/resources/image/" +
    // product.getProductId() + ".png");

    path = Paths.get("F:\\Spring\\eMusicStore\\src\\main\\webapp\\WEB-INF\\resources\\images\\"
            + product.getProductId() + ".png");

    if (productImage != null && !productImage.isEmpty()) {
        try {
            productImage.transferTo(new File(path.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Product image saving failed", e);
        }
    }
    return "redirect:/admin/productInventory";
}
+4
source share
1 answer

@ModelAttribute - / , @ModelAttribute("person") Person person , , age to Person . , . .

, Model model, , . , , @ModelAttribute

+2

Source: https://habr.com/ru/post/1660017/


All Articles