概述
HandlerMethodReturnValueHandler
是Spring Web
的一个策略接口,该类对象用于处理控制器方法的返回值。该接口定义了两个方法 :
boolean supportsReturnType(MethodParameter returnType)
检测该返回值是否被支持,通常是根据返回值的类型或者注解来判断;只有被支持的返回值类型才能被该
HandlerMethodReturnValueHandler
的另一个方法handleReturnValue
处理。void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception
处理返回值;只有被当前
HandlerMethodReturnValueHandler
的另一方法supportsReturnType
判断为支持的类型才能被该方法处理;该方法通常有两种处理结果分支:- 能够将请求处理完,此时会将相应的信息,比如头部,状态字,或者响应体设置到响应对象,然后标记
mavContainer
的属性requestHandled
为true
,告知调用者请求已被完全处理,无需继续处理该请求; - 不能将请求处理完,也有可能将部分信息设置到响应对象,比如头部,状态字等等,不过
mavContainer
的属性requestHandled
会是false
,告知调用者请求尚未处理完,需要继续处理,通常该请求下mavContainer
隐含了要渲染的视图和需要被渲染的数据模型,调用者随后会进行视图解析和视图渲染才标记成请求处理完成。
- 能够将请求处理完,此时会将相应的信息,比如头部,状态字,或者响应体设置到响应对象,然后标记
Spring
内置提供了很多HandlerMethodReturnValueHandler
的实现,具体可以参考:Spring Web : HandlerMethodReturnValueHandler 实现类清单
关于HandlerMethodReturnValueHandler
的使用,可以参考Spring MVC HandlerAdapter : RequestMappingHandlerAdapter
。
源代码
package org.springframework.web.method.support;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.NativeWebRequest;
public interface HandlerMethodReturnValueHandler {
/**
* Whether the given {@linkplain MethodParameter method return type} is
* supported by this handler.
* 是否支持处理某个返回值 returnType
* 注意 : 方法返回值 也被 Spring 叫做一个方法参数
* @param returnType the method return type to check
* @return {@code true} if this handler supports the supplied return type;
* {@code false} otherwise
*/
boolean supportsReturnType(MethodParameter returnType);
/**
* Handle the given return value by adding attributes to the model and
* setting a view or setting the
* {@link ModelAndViewContainer#setRequestHandled} flag to {@code true}
* to indicate the response has been handled directly.
* 处理控制器方法执行的返回值,将处理结果传播到 mavContainer 和 webRequest,
* 如果该方法实现逻辑能够将请求处理完,则调用 ModelAndViewContainer#setRequestHandled(true),
* 否则会将信息传播到 mavContainer 供调用者继续处理
* @param returnValue the value returned from the handler method
* @param returnType the type of the return value. This type must have
* previously been passed to {@link #supportsReturnType} which must
* have returned {@code true}.
* @param mavContainer the ModelAndViewContainer for the current request
* @param webRequest the current request
* @throws Exception if the return value handling results in an error
*/
void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception;
}