javarestmodel

What is the actual implementation of Model in Spring MVC


A lot of people have answered that Model is an interface while ModelView is a class implementing Map interface.

  1. My confusion is what actually implements interface Model then? (I am a beginner of Spring MVC so please be patient You can refer to this thread for code hint. What are the differences between Model, ModelMap, and ModelAndView?

  2. More interestingly, I saw someone just use Map<> interface:

// When the path is routed to '/new' below method to be called and view //returned is newPokemon

    @RequestMapping(method = RequestMethod.GET, value ="/new")

        public String newPokemonForm(Map<String, Object> model) {
        Pokemon Pokemon = new Pokemon();
        model.put("pokemon", Pokemon);
        return "newPokemon";
    }

So I am thinking for this model parameter, Map<> should be declared type while modelmap is the actual type? Can anyone clarify with me? Thanks a lot

----------------------------------Update----------------------------

For the first question, actually it is easy to check in Intellij. Just open the source code package thanks to Elmar Brauch. see screenshot below: screenshot of finding the related source code


Solution

  • If you configure your build tool to download sources, you can just open Spring's Model interface. The type hierarchy (you can open it in Eclipse) shows you, that the following classes implement Model interface:

    In both classes you can see that they extend some kind of Map-class, which implements in a super class the Map interface.

    At runtime You can figure out, which type is used as implementation of Map interface. Set a breakpoint and inspect in debug mode or do something like this:

    @PostMapping
    public void postMap(@RequestBody Map map) {
        System.out.println(map.getClass());
    }
    

    This prints for my with @RestController annotated class this type: class java.util.LinkedHashMap