哪个更好,返回“ModelAndView”或“字符串”在 spring3 控制器上
返回 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 的方式
@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";
}
这些工作原理是一样的。哪个是更好的方法?和有什么区别?
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;
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有更好的办法了。两者都是完全有效的。您选择使用哪一种取决于哪一种更适合您的应用程序 - Spring 允许您使用任何一种方式。
从历史上看,这两种方法来自不同版本的 Spring。
ModelAndView
方法是 Spring 2.0 之前从控制器返回模型和视图信息的主要方式。现在您可以将Model
参数和String
返回值结合起来,但旧方法仍然有效。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.
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 theModel
parameter and theString
return value, but the old approach is still valid.我也想加我2分钱。第二种方法更倾向于面向约定,即开发人员确实明确提到了他的视图是什么,但其隐含的是返回字符串是视图名称。所以编码少,可读性强,标准。比使用 ModelAndView 的旧方法好得多
I would like to add me 2 cents also. Second approach is more towards convention oriented i.e developer does explicitly mention what is his view but its implicit that return string is view name. So less coding,readable and standard. Much better than older way with ModelAndView