Spring MVC 控制器方法的有效返回类型是什么? [英] What are valid return types of a Spring MVC controller method?

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

问题描述

我在 Spring MVC 方面没有太多经验,我有以下关于控制器方法可以返回的有效返回类型是什么.

I have not much experience in Spring MVC and I have the following about what are the valids return types that a controller method can return.

所以我知道用户生成了一个由 DispatcherServlet 接收和处理的 HttpRequest,该DispatcherServlet 将该请求分派给特定的控制器类.

So I know that the user generate an HttpRequest received and handled by the DispatcherServlet that dispatch this request to a specific controller class.

控制器类是这样的:

@Controller
public class AccountController {

    @RequestMapping("/showAccount")
    public String show(@RequestParam("entityId") long id, Model model) {
        ...
    }

    .......................................
    .......................................
    .......................................
}

所以我知道每个方法处理一个特定的请求,并且处理的请求由 @RequestMapping 注释指定.

So I know that each method handle a specific request and that the handled request is specified by the @RequestMapping annotation.

我也知道该方法返回一个 String 对象,该对象是逻辑视图名称(然后由视图解析器解析为渲染视图)

I also know that the method return a String object that is the logical view name (that then is resolved by the view resolver to render the view)

所以,在这个阶段,我认为控制器类的方法只返回 String 对象.但我不确定.也许这样的方法也可以返回一些不同类型的对象?

So, at this stage, I think that a method of a controller class returns only String object. But I am not sure of it. Maybe a method like this can return also some different kind of objects?

推荐答案

Handler 方法有很多返回类型可用,在控制器内部由 @RequestMapping 注释,例如:

There are many return types are available for Handler method which is annotated by @RequestMapping inside the controller, like :

  • ModelAndView(类)

  • ModelAndView (Class)

模型(接口)

还有更多.....查看文档

每个返回类型都有其特定用途,例如:如果您使用的是字符串,则表示返回视图名称,并且该视图名称将由 ViewResolver 解析.如果您不想返回任何视图名称,请提及返回类型为 void.如果您想设置视图名称以及发送一些数据来查看,请使用 ModelAndView 作为返回类型.

Every return type have its specific use for example: If you are using String then it means return View Name and this view name will resolved by ViewResolver. If you don't want to return any view name mention return type as void. If you want to set view name as well as want to send some data to view use ModelAndView as a return type.

请仔细阅读文档,您还将了解可以在处理程序方法中传递什么样的方法参数.

Please go through the documentation you will also get to know what kind of method argument you can pass in the handler method.

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

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