What are the differences between Model, ModelMap, and ModelAndView?

前端 未结 3 1221
旧时难觅i
旧时难觅i 2020-11-30 20:42

What are the main differences between the following Spring Framework classes?

  • Model
  • ModelMap
  • ModelAndView
相关标签:
3条回答
  • 2020-11-30 21:11

    Differences between Model, ModelMap, and ModelAndView

    Model: It is an Interface. It defines a holder for model attributes and primarily designed for adding attributes to the model.

    Example:

    @RequestMapping(method = RequestMethod.GET)
        public String printHello(Model model) {
              model.addAttribute("message", "Hello World!!");
              return "hello";
           }
    

    ModelMap: Implementation of Map for use when building model data for use with UI tools.Supports chained calls and generation of model attribute names.

    Example:

    @RequestMapping("/helloworld")
    public String hello(ModelMap map) {
        String helloWorldMessage = "Hello world!";
        String welcomeMessage = "Welcome!";
        map.addAttribute("helloMessage", helloWorldMessage);
        map.addAttribute("welcomeMessage", welcomeMessage);
        return "hello";
    }
    

    ModelAndView: This class merely holds both to make it possible for a controller to return both model and view in a single return value.

    Example:

    @RequestMapping("/welcome")
    public ModelAndView helloWorld() {
            String message = "Hello World!";
            return new ModelAndView("welcome", "message", message);
        }
    
    0 讨论(0)
  • 2020-11-30 21:11

    Model: is an interface it contains four addAttribute and one merAttribute method.

    ModelMap: implements Map interface. It also contains Map method.

    ModelAndView: As Bart explain it allows a controller return both as a single value.

    0 讨论(0)
  • 2020-11-30 21:14

    Model is an interface while ModelMap is a class.

    ModelAndView is just a container for both a ModelMap and a view object. It allows a controller to return both as a single value.

    0 讨论(0)
提交回复
热议问题