1

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;
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
Jack
  • 6,430
  • 27
  • 80
  • 151

1 Answers1

1

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    it does not accept addObject methods anymore! Imported library is org.springframework.ui.Model; I suppose I should replace them with addAttribute right? – Jack Mar 18 '15 at 05:25