Spring MVC:将Model作为参数传递给控制器​​方法VS显式实例化它 [英] Spring MVC: Passing a Model as an argument to a controller method VS instantiating it explicitly

查看:55
本文介绍了Spring MVC:将Model作为参数传递给控制器​​方法VS显式实例化它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MVC Controller 类中创建了两个测试方法。在第一种方法中, Model 作为参数传递,在第二种方法中我直接实例化它。在这两种方法中,我向模型实例添加了一个属性:

I have created two test methods in my MVC Controller class. In the first method the Model is being passed as an argument and in the second one I instantiate it directly. In both methods I add a single attribute to the Model instance:

@RequestMapping("/test-modelParam")
public String testMethod1(Model model) {
    model.addAttribute("testname", "testvalue");
    return "/testview";
}


@RequestMapping("/test-modelInstantiatedExplicitly")
public ModelAndView testMethod2() {
    ModelAndView mav = new ModelAndView("/testview");
    mav.addObject("testname", "testvalue");
    return mav;
}

在这两种情况下,View都会正确填充。

The View gets populated correctly in both cases.

这两种方法有什么区别吗?如果是这样的话,在哪里优先使用一个?

Is there any difference between the two approaches? If so, Where is it preferred to use one over the other?

推荐答案

最终没有任何区别一切都会结束最终在 ModelAndView 中。

In the end there is no difference everything will end up in a ModelAndView eventually.

当使用模型 ModelMap 作为方法时参数将预先填充一些值

When using the Model or ModelMap as a method argument it will get pre-populated with some values


  1. 路径变量

  2. 任何<$的结果c $ c> @ModelAttribute 带注释的方法

  3. 控制器可用的任何 @SessionAttribute

  1. Path Variables
  2. Result of any @ModelAttribute annotated methods
  3. Any @SessionAttributes available to the controller

简而言之,它是该方法可用的预先填充的模型。

In short it is the pre-populated model made available to the method.

模型始终是创建的,并与您使用 ModelAndView 。

The Model is always created and is merged with the one you add/create with a ModelAndView.

这篇关于Spring MVC:将Model作为参数传递给控制器​​方法VS显式实例化它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆