0
@RequestMapping(value="/addpost",method=RequestMethod.POST)
    public ModelAndView addpost(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("r") Reg reg)
    {
        int id=r.id;
        System.out.println(id);
        return mv;
    }

In this code,there is given @ModelAttribute("r") Reg reg.Wether this modelattribute is taking values from jsp page?Can anyone explains the working of this ModelAttribute?

Swati
  • 13
  • 7

1 Answers1

0

There are two usage of @ModelAttribute

At the Method Level

When the annotation is used at the method level it indicates the purpose of that method is to add one or more model attributes. Such methods support the same argument types as @RequestMapping methods but that cannot be mapped directly to requests.

@ModelAttribute
public void addAttributes(Model model) {
    model.addAttribute("msg", "Welcome to the Netherlands!");
}

In the example, method adds an attribute named msg to all models defined in the controller class.

As a Method Argument

When used as a method argument, it indicates the argument should be retrieved from the model. When not present, it should be first instantiated and then added to the model and once present in the model, the arguments fields should be populated from all request parameters that have matching names.

In the code snippet that follows the employee model attribute is populated with data from a form submitted to the addEmployee endpoint.

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") Employee employee) {
    // Code that uses the employee object

    return "employeeView";
}

Refer : What is @ModelAttribute in Spring MVC?

Alin
  • 314
  • 1
  • 3
  • 9