简体   繁体   中英

Spring MVC annotation @ModelAttribute

i have some question about Spring MVC annotation @ModelAttribute. In first method named as "addProduct" i create Model model and after call model.addAttribute i can use "product" name in jsp file,for example product.getProductPrice. But in second method named same as first,i added parameter " @ModelAttribute("product") Product product ",but why?? If i will delete this annotation, my program works as same as before,please explain me) Thank you very much,sorry for my English,i am 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";
}

Purpose @ModelAttribute is bind param/properties from request a model object, say @ModelAttribute("person") Person person in your method, it will bind properties from object such name, age to Person and construct a object out of it. It does not pass anything to your view, it job finishes once the request submitted. Not carried down to the view of that action.

In contrast, when you have Model model you are explicitly constructing an object with property added to its attribute. It will be carried down to your view unlike what @ModelAttribute does above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM