Spring MVC控制器返回类型 [英] Spring MVC Controllers Return Type

查看:98
本文介绍了Spring MVC控制器返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过一些示例,其中控制器返回一个String(指示视图)

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"
}

我还看到了一些示例,其中控制器返回"ModelAndView"对象类型

And I also see examples where a controller returns a "ModelAndView" object type

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.

推荐答案

如果我们谈论的是MVC 3,那么两者都是正确的.但是直接返回ModelAndView是旧的方式,而且更直观.

If we are talking about MVC 3, than, both are correct. But directly returning ModelAndView is the old way, and more verbal.

如果您仅返回一个字符串(不带@ResponseBody,则为其他字符串),则将该字符串视为视图名称,并且spring将其推入视图解析器中-因此,您不必担心(至少在编写控制器),将使用哪种类型的视图渲染器(不管是jsp还是speed,都没有关系).您仅传播Model实例,然后返回一个提示,下一步该怎么做.正确的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 Model instance, and returnes a hint what to do with it next. Proper ModelAndView object is made later internally by string.

通常,spring 3为您提供更多的参数和返回类型灵活性(请参见

Generally, spring 3 gives you more flexibility with arguments and return types (see Defining @RequestMapping handler methods section in Spring documentaton).

这篇关于Spring MVC控制器返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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