javaspring-mvcmodelandview

Is it alright to create an object of modelandview in each method of the class?


I have following controller which is serving different requests. I am wondering if the way that I create ModelAndView is correct? I am creating one object in each method. Is there any better approach?

@RequestMapping(method = RequestMethod.GET)
public ModelAndView showNames() {
    ...
    ModelAndView model = new ModelAndView("names");
    model.addObject ....
    return model;
}

@RequestMapping(value = "/name/{name}", method = RequestMethod.GET)
public ModelAndView showNameDetails(@PathVariable String name) {
    ...
    ModelAndView model = new ModelAndView("name");
    model.addObject ...
    return model;
}

@RequestMapping(value = "/name/{name}/{item}", method = RequestMethod.GET)
public ModelAndView showItemsOfName(@PathVariable String name,
        @PathVariable String item) {
    ...
    ModelAndView model = new ModelAndView("item");
    model.addObject ....
    return model;
}

Solution

  • You can ask Spring to inject the Model for you, and then return the view name from the method, e.g.

    @RequestMapping(method = RequestMethod.GET)
    public String showNames(Model model) {
        ...
        model.addObject ....
        return "names";
    }
    
    @RequestMapping(value = "/name/{name}", method = RequestMethod.GET)
    public String showNameDetails(@PathVariable String name, Model model) {
        ...
        model.addObject ...
        return "name";
    }
    
    @RequestMapping(value = "/name/{name}/{item}", method = RequestMethod.GET)
    public String showItemsOfName(@PathVariable String name,
            @PathVariable String item, Model model) {
        ...
        model.addObject ....
        return "item";
    }
    

    It's a bit cleaner, and less code.