Home > OS >  Using Map<String, Object> instead of org.springframework.ui.Model to populate view
Using Map<String, Object> instead of org.springframework.ui.Model to populate view

Time:10-26

Apologies if this is too vague, I'm new to Spring. 95% examples I've seen for spring controllers use something like Model or ModelAndView to add attributes to pass to the view. Something like this:

@GetMapping("/")
public String home(Model model) {
    model.addAttribute(....);
    ...
    return "home";
}

but very rarely I encounter this:

public String home(Map<String, Object> model) {
    model.put(...);
    ...
    return "home";
}

Which seems to work fine as well. Is the latter an older approach? Also, where can one find documentation on methods annotated by specific annotations (eg. @RequestMapping)? ie. not documentation on the parameters to the annotation itself, but on parameters passed to java methods/classes annotated by these annotations. For eg. the spring docs for @RequestMapping don't give any information about things like Model/ModelAndView so I'm confused how methods annotated this way work in terms of where they get the Model object (or indeed Map<String, Object>) from

CodePudding user response:

spring mvc uses MapMethodProcessor to resolve the parameters of the Map type in the function. When parsing the parameters of this type, it actually gets the defaultModel object in the ModelAndViewContainer object in the current request, and the defaultModel object is Map Subclass (BindingAwareModelMap), so the only difference between the two methods is that one explicitly lets you know you're using a Model object, and the other makes you think you're using a HashMap or some other Map subclass object, but it's actually BindingAwareModelMap, which is Model objectenter image description heres.

  • Related