Spring MVC 控制器返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7383622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC Controllers Return Type
提问by Girish Dusane
I've seen examples where a controller returns a String (which indicates the view)
我见过控制器返回字符串(表示视图)的示例
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner"
}
And I also see examples where a controller returns a "ModelAndView" object type
我还看到控制器返回“ModelAndView”对象类型的示例
public ModelAndView helloWorld() {
ModelAndView mav = new ModelAndView();
mav.setViewName("helloWorld");
mav.addObject("message", "Hello World!");
return mav;
}
What is the difference between the two and which should I use? Cause either way I can get my view resolved.
两者有什么区别,我应该使用哪个?因为无论哪种方式,我都可以解决我的观点。
采纳答案by Adam Jurczyk
If we are talking about MVC 3, than, both are correct. But directly returning ModelAndView is the old way, and more verbal.
如果我们谈论的是 MVC 3,那么两者都是正确的。但是直接返回 ModelAndView 是老办法了,而且比较啰嗦。
If you are returning just a string (without @ResponseBody which is something else), this string is treated as view name, and spring pushes it to view resolvers - so, you dont have to worry (at least, while you are writing controllers), what type of view renderer you'll use (let it be jsp or velocity, it doesn't matter). You only propagate the Modelinstance, and returnes a hint what to do with it next. Proper ModelAndViewobject is made later internally by string.
如果你只返回一个字符串(没有 @ResponseBody 这是别的东西),这个字符串被视为视图名称,并且 spring 将它推送到视图解析器 - 所以,你不必担心(至少,在你编写控制器时) ,你将使用什么类型的视图渲染器(不管是jsp还是velocity,都无所谓)。您只传播Model实例,并返回一个提示,下一步如何处理它。适当的ModelAndView对象稍后由字符串在内部生成。
Generally, spring 3 gives you more flexibility with arguments and return types (see Defining @RequestMapping handler methodssection in Spring documentaton).
通常,spring 3 在参数和返回类型方面为您提供了更大的灵活性(请参阅Spring 文档中的定义 @RequestMapping 处理程序方法部分)。
回答by Thomas
It's the same logic but it's not the same version of spring.
这是相同的逻辑,但它不是相同版本的 spring。
The ModelAndView object is the spring 2.x way of handling model and views. In the example you gave, the modelandview object will load the "helloWorld" view (depending on your templating engine could be helloWorld.jsp, or helloWorld.html, ...) with one data "message" in the model.
ModelAndView 对象是 spring 2.x 处理模型和视图的方式。在您给出的示例中,modelandview 对象将加载“helloWorld”视图(取决于您的模板引擎可以是 helloWorld.jsp 或 helloWorld.html,...),模型中带有一个数据“消息”。
The other way is the spring 3.x way. You could have wrote exactly the same example as your helloworld.
另一种方式是 spring 3.x 方式。您可以编写与 helloworld 完全相同的示例。
@RequestMapping(value="/helloWorld", method=RequestMethod.GET)
public String helloWorld(Model model) {
model.addAttribute("message", "Hello World!");
return "helloWorld";
}
The model is automaticly populated at request.
模型会根据要求自动填充。
And we can simplify this notation as the url mapping "helloWorld" is directly the view name.
我们可以简化这个表示法,因为 url 映射“helloWorld”直接是视图名称。
@RequestMapping(value="/helloWorld", method=RequestMethod.GET)
public void helloWorld(Model model) {
model.addAttribute("message", "Hello World!");
}
the helloWorld view will be automaticly loaded
helloWorld 视图将自动加载
回答by danny.lesnik
In Spring MVC, you should return ModelAndView if you want to render jsp page
在 Spring MVC 中,如果要呈现 jsp 页面,则应返回 ModelAndView
For example:
例如:
@RequestMapping(value="/index.html", method=RequestMethod.GET)
public ModelAndView indexView(){
ModelAndView mv = new ModelAndView("index");
return mv;
}
this function will return index.jsp when you are hitting /index.html
当您点击 /index.html 时,此函数将返回 index.jsp
In addition you can return any JSON or XML object using @ResponseBodyannotation and serializer.
此外,您可以使用@ResponseBody注释和序列化程序返回任何 JSON 或 XML 对象。
For example:
例如:
@RequestMapping(value="/getStudent.do",method=RequestMethod.POST)
@ResponseBody
public List<Student> getStudent(@RequestParam("studentId") String id){
List<Student> students = daoService.getStudent(id);
return students;
}
In this example you will return List as JSON in case and you have enabled Hymanson serializer. In order to enable that you need to add the following to your Spring XML:
在此示例中,您将 List 作为 JSON 返回,以防万一并且您启用了 Hymanson 序列化程序。为了启用它,您需要将以下内容添加到您的 Spring XML 中:
<context:annotation-config/>
And the Serializer itself:
和序列化器本身:
<bean id="HymansonMessageConverter" class="org.springframework.http.converter.json.MappingHymansonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="HymansonMessageConverter"/>
</list>
</property>
</bean>
Hope it helps.
希望能帮助到你。
回答by kalyan
Returning ModelAndView or a string does the same job. It resolves into a view (a jsp page) and giving a model object to be rendered in the view. If you return a string, spring internally resolves to a view using viewResolver, create a ModelAndView Object and return it. The returning of ModelAndView object is from the older version. You can do either of this based on your convenient.
返回 ModelAndView 或字符串执行相同的工作。它解析为一个视图(一个 jsp 页面)并给出一个要在视图中呈现的模型对象。如果你返回一个字符串,spring 会使用 viewResolver 在内部解析为一个视图,创建一个 ModelAndView 对象并返回它。ModelAndView 对象的返回来自旧版本。您可以根据自己的方便来执行此操作。
Have a look at this question
看看这个问题
Also bunch of answers are pointing out to @RequestBody. Its not exactly related to your question. But keep in mind that it will convert your object based on content-type using available converters and the resuly will be part of the document body.
还有一堆答案指向@RequestBody。它与您的问题并不完全相关。但请记住,它将使用可用的转换器根据内容类型转换您的对象,并且结果将成为文档正文的一部分。
回答by Arun P Johny
If you are using a template language like freemarker or velocity to create the response then you can return the ModelAndView.
如果您使用像 freemarker 或 Velocity 这样的模板语言来创建响应,那么您可以返回ModelAndView.
If you want to return a json/xml or some string as the response(ex: ajax requests) then you can use the first method. I think it should be public @ResponseBody String findOwner(@PathVariable String ownerId, Model model), you need to add a annotation called @ResponseBodyto indicate that the returned value should be converted as the response text. Using @ResponseBodywill enable you to use libraries like Hymansonor JaxBto create json/xml responses respectively.
如果您想返回一个 json/xml 或一些字符串作为响应(例如:ajax 请求),那么您可以使用第一种方法。我觉得应该是public @ResponseBody String findOwner(@PathVariable String ownerId, Model model),你需要添加一个名为@ResponseBody的注解来指示返回值应该被转换为响应文本。Using@ResponseBody将使您能够使用Hymanson或JaxB 之类的库分别创建 json/xml 响应。
These returned values will be converted using the messageConvertersregistered with AnnotationMethodHandlerAdapter.
这些返回值将使用messageConverters注册的AnnotationMethodHandlerAdapter.
Ref: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
参考:http: //blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/
回答by Janarthanan Ramu
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner"
}
in this method the return type is String and we adding Model as a parameter so to add a value with model we will add like
在这个方法中,返回类型是字符串,我们添加模型作为参数,以便为模型添加一个值,我们将添加如下
modelparam.addAttribute("obj",value);
and return to the displayowner to jsp as per view resolver
并根据视图解析器返回显示所有者到jsp
public ModelAndView helloWorld() {
ModelAndView mav = new ModelAndView();
mav.setViewName("helloWorld");
mav.addObject("message", "Hello World!");
return mav;
}
in this method the return type is ModelAndView so we will return the model and here the mav is the object of ModelAndView so here we should add like
在这个方法中,返回类型是 ModelAndView 所以我们将返回模型,这里 mav 是 ModelAndView 的对象,所以在这里我们应该添加像
model.addObject("object","value");
here the viewname is returned to helloworld.jsp as per the viewResolver
这里视图名根据 viewResolver 返回到 helloworld.jsp

