天天看点

Spring MVC源码解析:返回值处理器,处理多种返回值类型

Spring MVC源码解析:返回值处理器,处理多种返回值类型

Handler可以返回多种类型

其实@RequestMapping方法可以返回多种类型的数据,但是我们现在基本上都只会用@ResponseBody这种方式,别的方式基本上不会使用了。

Handler可以返回的类型如下(从官网截图,只截图了一部分)

Spring MVC源码解析:返回值处理器,处理多种返回值类型

其他返回String,View等类型的方式在Spring MVC时代还挺常见的。找了一个之前的Spring MVC项目,给大家演示一下其他返回值类型的处理

Spring MVC源码解析:返回值处理器,处理多种返回值类型
Spring MVC源码解析:返回值处理器,处理多种返回值类型

index.jsp

Spring MVC源码解析:返回值处理器,处理多种返回值类型
Spring MVC源码解析:返回值处理器,处理多种返回值类型

notice.jsp

Spring MVC源码解析:返回值处理器,处理多种返回值类型
Spring MVC源码解析:返回值处理器,处理多种返回值类型

方法或者类上加了@ResponseBody注解,则会直接返回json,xml等内容。

方法或者类上没有加@ResponseBody注解,返回了String,View或者ModelAndView等时则会解析为相应的试图返回。

可以看到根据不同的返回值,需要执行不同的解析逻辑,这时就需要HandlerMethodReturnValueHandler(返回值处理器),根据不同的返回值调用相应的HandlerMethodReturnValueHandler来处理

Spring MVC源码解析:返回值处理器,处理多种返回值类型
Spring MVC源码解析:返回值处理器,处理多种返回值类型

HandlerMethodReturnValueHandlerComposite#handleReturnValue

Spring MVC源码解析:返回值处理器,处理多种返回值类型
Spring MVC源码解析:返回值处理器,处理多种返回值类型

找到第一个支持特定返回值的返回值处理器,然后处理返回值

Spring MVC源码解析:返回值处理器,处理多种返回值类型

RequestResponseBodyMethodProcessor同时实现了HandlerMethodArgumentResolver接口

和HandlerMethodReturnValueHandler接口,所以既是参数处理器,也是返回值处理器

HandlerMethodArgumentResolver:用来支持@RequestBody注解

HandlerMethodReturnValueHandler:用来支持@ResponseBody注解

ViewNameMethodReturnValueHandler

Spring MVC源码解析:返回值处理器,处理多种返回值类型

用来处理返回值类型是void或者字符串

将试图相关的信息放到ModelAndViewContainer中,后续会根据ModelAndViewContainer中的值创建ModelAndView

RequestResponseBodyMethodProcessor

RequestResponseBodyMethodProcessor#supportsReturnType

Spring MVC源码解析:返回值处理器,处理多种返回值类型

方法上或者类上有ResponseBody注解,则利用RequestResponseBodyMethodProcessor来处理返回值RequestResponseBodyMethodProcessor#handleReturnValue

Spring MVC源码解析:返回值处理器,处理多种返回值类型

可以看到首先执行mavContainer.setRequestHandled(true),这样handler返回的ModelAndView为null,就不会进行视图渲染的过程方法里面会利用HttpMessageConverter来进行报文和对象的转换。

Spring MVC源码解析:返回值处理器,处理多种返回值类型

参考博客