1

我有以下控制器,它服务于不同的请求。我想知道我创建 ModelAndView 的方式是否正确?我在每种方法中创建一个对象。有没有更好的方法?

@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;
}
4

1 回答 1

1

您可以要求 Spring 为您注入模型,然后从方法中返回视图名称,例如

@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";
}

它更干净,代码更少。

于 2015-03-18T05:14:55.783 回答