问题描述
返回ModelAndView的方式
The way of return ModelAndView
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ModelAndView list(
@UserAuth UserAuth user,
ModelAndView mav) {
if (!user.isAuthenticated()) {
mav.setViewName("redirect:http://www.test.com/login.jsp");
return mav;
}
mav.setViewName("list");
mav.addObject("articles", listService.getLists());
return mav;
}
返回String的方式
The way of return String
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(
@UserAuth UserAuth user,
Model model) {
if (!user.isAuthenticated()) {
return "redirect:http://www.test.com/login.jsp";
}
model.addAttribute("articles", listService.getLists());
return "list";
}
这是更好的方法?有什么区别?
These work same. which is better way? and what is difference?
推荐答案
没有更好的方法。两者都是完全有效的。
There is no better way. Both are perfectly valid. Which one you choose to use depends which one suits your application better - Spring allows you to do it either way.
历史上,这两种方法来自不同的Spring版本。 ModelAndView
方法是在Spring 2.0之前从控制器返回模型和视图信息的主要方法。现在你可以结合 Model
参数和 String
返回值,但是旧的方法仍然有效。
Historically, the two approaches come from different versions of Spring. The ModelAndView
approach was the primary way of returning both model and view information from a controller in pre-Spring 2.0. Now you can combine the Model
parameter and the String
return value, but the old approach is still valid.
这篇关于哪个更好,返回“ModelAndView”或“字符串”在spring3控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!