在class的每个方法中创建一个modelandview的对象可以吗?

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

我有以下控制器正在处理不同的请求。我想知道我创建 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;
}

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

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

更简洁,代码更少。