哪个更好,返回“ModelAndView”或“字符串”在 spring3 控制器上

发布于 2024-12-01 13:10:42 字数 822 浏览 2 评论 0原文

返回 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡写薰衣草的香 2024-12-08 13:10:42

没有更好的办法了。两者都是完全有效的。您选择使用哪一种取决于哪一种更适合您的应用程序 - 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 the Model parameter and the String return value, but the old approach is still valid.

瞄了个咪的 2024-12-08 13:10:42

我也想加我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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文