【问题标题】:SpringMVC @RequestMapping return String ModelAndViewSpringMVC @RequestMapping 返回字符串 ModelAndView
【发布时间】:2018-12-27 07:45:33
【问题描述】:

我有两种 spring MVC @RequestMapping return 方法,但我不知道 如何选择 请问这两种方法的区别???

//返回模型和视图

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

【问题讨论】:

  • 从功能上看没有区别。

标签: spring spring-mvc


【解决方案1】:

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

这里是相关的 SO 答案

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

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

来自docs

字符串

要使用 ViewResolver 解析并与 隐式模型 —— 通过命令对象和 @ModelAttribute 方法。处理程序方法也可以以编程方式 通过声明模型参数来丰富模型(见上文)。

ModelAndView 对象

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

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

【讨论】:

    【解决方案2】:

    虽然你的班级不见了,但我可以给出一个区别

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

    将返回一个字符串“login”。 @RestController 有所作为

    【讨论】:

    • 对不起,因为我使用 @Controller 但我认为它正在工作“@RequestMapping”
    猜你喜欢
    • 2017-10-11
    • 2018-07-07
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2015-02-10
    相关资源
    最近更新 更多