简体   繁体   中英

Welcome page in spring form

Why we returned ModelAndView in showForm() method of Controller class when using Spring Form.

@Controller
public class EmployeeController {

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public ModelAndView showForm() {
        return new ModelAndView("employeeHome", "employee", new Employee());
    }

    @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    public String submit(@Valid @ModelAttribute("employee")Employee employee, 
      BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "error";
        }
        model.addAttribute("name", employee.getName());
        model.addAttribute("contactNumber", employee.getContactNumber());
        model.addAttribute("id", employee.getId());
        return "employeeView";
    }
}

If you return a String from a controller method its value is treated as the name of a view you want to show to the user. While rendering the view the data is taken from Model or ModelMap instance, which you pass to the method as a parameter and fill with your data in the method body.

    model.addAttribute("name", employee.getName());
    model.addAttribute("contactNumber", employee.getContactNumber());
    model.addAttribute("id", employee.getId());
    return "employeeView";

If you return ModelAndView, however, the name of the view as well as the data needed to render the view are both taken from the single returned instance.

return new ModelAndView("employeeHome", "employee", new Employee());

Here you return an instance of ModelAndView, which carries the name of the view('employeeHome') and data represented by an Employee object inside an attribute named 'employee'.

The difference in use of each option is insignificant, so use whatever you feel is more convenient to you.

Also you might want to check out this article to get a more clear understanding: https://www.baeldung.com/spring-mvc-model-model-map-model-view

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