SpringMVC @RequestMapping返回String ModelAndView

时间:2018-07-19 08:42:38

标签: spring spring-mvc

我有两种方法可以使Spring MVC @RequestMapping返回,但我不知道 如何选择 我想问一下这两种方法之间的区别吗?

//返回ModelAndView

@RequestMapping(value = "/loginRetunModel", method = RequestMethod.GET)
public ModelAndView redirectModel(HttpServletRequest request, HttpServletResponse response) 
{
    return new ModelAndView("login");
}

//返回字符串

@RequestMapping(value = "/loginReturnString", method = RequestMethod.GET)
public String redirectString(HttpServletRequest request, HttpServletResponse response)
{
    return "login";
}

2 个答案:

答案 0 :(得分:0)

正如Deinum M.指出的那样,映射结果没有区别。

这里有相关的答案

What are valid return types of a Spring MVC controller method?

Which return type use in spring mvc in @RequestMapping method?

来自docs

  

字符串

     

要用ViewResolver解析的视图名称,并与   隐式模型-通过命令对象确定   @ModelAttribute方法。该处理程序方法也可以以编程方式   通过声明Model参数来丰富模型(请参见上文)。

     

ModelAndView对象

     

要使用的视图和模型属性,以及可选的响应   状态。

基本上,String返回类型用于声明要显示的视图的名称,而ModelAndView提供了额外添加模型属性的可能性。

答案 1 :(得分:0)

尽管您的课程失踪了,我还是可以给一个区别

@Controller
public class AccountController {

    @RequestMapping(value = "/loginReturnString", method = RequestMethod.GET)
    public String redirectString(HttpServletRequest request, HttpServletResponse response)
    {
      return "login";
    }

将根据解析的视图返回 login.jsp 或其他扩展名。

但是

@RestController
public class AccountController {

    @RequestMapping(value = "/loginReturnString", method = RequestMethod.GET)
    public String redirectString(HttpServletRequest request, HttpServletResponse response)
    {
      return "login";
    }

将返回字符串“登录” 。 @RestController有所作为

相关问题