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";
}
Productinside the controller and putting it in the model. In the second case, you're getting theProductinformation from the request contents. (And for heaven's sake, don't hard-code insane file manipulation like that! If you have to have something like that, use a property with@Valueto specify it.)@SessionAttributesyou will see weird behavior.