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

问题描述

我在Spring MVC上没有太多经验,我有以下关于控制器方法可以返回的valids返回类型的内容

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.

所以我知道用户生成一个 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)

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

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)

模型(界面)

等等......

每次返回type有其特定用途,例如:如果您使用String,则表示返回View Name,此视图名称将由 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控制器方法的有效返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:11