Request过程
Handler实际执行请求(request)
DispatcherServlet: doDispatch
|
AbstractHandlerMethodAdapter: handle
|
RequestMappingHandlerAdapter: handleInternal
RequestMappingHandlerAdapter: invokeHandlerMethod
|
ServletInvocableHandlerMethod: invokeAndHandle
|
InvocableHandlerMethod: invokeForRequest
InvocableHandlerMethod: getMethodArgumentValues
|
HandlerMethodArgumentResolverComposite: resolveArgument
|
RequestResponseBodyMethodProcessor:resolveArgument
|
RequestResponseBodyMethodProcessor:readWithMessageConverters
|
AbstractMessageConverterMethodArgumentResolver: readWithMessageConverters
AbstractMessageConverterMethodArgumentResolver
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
....
try {
inputMessage = new EmptyBodyCheckingHttpInputMessage(inputMessage);
// messageConverters :启动时加载到容器中
for (HttpMessageConverter<?> converter : this.messageConverters) {
Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
....
// 判断转换器是否支持参数类型
if (converter.canRead(targetClass, contentType)) {
if (inputMessage.getBody() != null) {
// read前操作
inputMessage = getAdvice().beforeBodyRead(inputMessage, parameter, targetType, converterType);
// read方法执行HTTP报文到参数的转换
body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage);
body = getAdvice().afterBodyRead(body, inputMessage, parameter, targetType, converterType);
}
else {
body = getAdvice().handleEmptyBody(null, inputMessage, parameter, targetType, converterType);
}
break;
}
...
}
}
catch (IOException ex) {
throw new HttpMessageNotReadableException("I/O error while reading input message", ex);
}
....
return body;
}
Response过程
Handler实际执行请求(response)
DispatcherServlet: doDispatch
|
AbstractHandlerMethodAdapter: handle
|
RequestMappingHandlerAdapter: handleInternal
RequestMappingHandlerAdapter: invokeHandlerMethod
|
ServletInvocableHandlerMethod: invokeAndHandle
|
InvocableHandlerMethod: handleReturnValue
|
HandlerMethodArgumentResolverComposite: handleReturnValue
|
RequestResponseBodyMethodProcessor:handleReturnValue
|
AbstractMessageConverterMethodProcessor:writeWithMessageConverters
AbstractMessageConverterMethodProcessor
protected <T> void writeWithMessageConverters(@Nullable T value, MethodParameter returnType,
ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)
throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {
...
for (HttpMessageConverter<?> converter : this.messageConverters) {
GenericHttpMessageConverter genericConverter = (converter instanceof GenericHttpMessageConverter ?
(GenericHttpMessageConverter<?>) converter : null);
if (genericConverter != null ?
// 判断转换器是否支持参数类型
((GenericHttpMessageConverter) converter).canWrite(targetType, valueType, selectedMediaType) :
converter.canWrite(valueType, selectedMediaType)) {
// write前的操作
body = getAdvice().beforeBodyWrite(body, returnType, selectedMediaType,
(Class<? extends HttpMessageConverter<?>>) converter.getClass(),
inputMessage, outputMessage);
if (body != null) {
Object theBody = body;
LogFormatUtils.traceDebug(logger, traceOn ->
"Writing [" + LogFormatUtils.formatValue(theBody, !traceOn) + "]");
addContentDispositionHeader(inputMessage, outputMessage);
if (genericConverter != null) {
genericConverter.write(body, targetType, selectedMediaType, outputMessage);
}
else {
// converter 将结果写入 response
((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage);
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Nothing to write: null body");
}
}
return;
}
}
...
}
MessageConverter从何而来
WebMvcConfigurationSupport
protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
stringConverter.setWriteAcceptCharset(false);
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(stringConverter);
messageConverters.add(new ResourceHttpMessageConverter());
messageConverters.add(new SourceHttpMessageConverter<Source>());
messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (jackson2Present) {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build();
messageConverters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}
else if (gsonPresent) {
messageConverters.add(new GsonHttpMessageConverter());
}
}
RequestResponseBodyAdvice从何而来
RequestMappingHandlerAdapter完成初始化过程
RequestMappingHandlerAdapter: afterPropertiesSet
RequestMappingHandlerAdapter: getDefaultArgumentResolvers
|
RequestResponseBodyMethodProcessor AbstractMessageConverterMethodProcessor: new
|
RequestResponseBodyAdviceChain: new
RequestMappingHandlerAdapter
private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() {
List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();
// Annotation-based argument resolution
// @RequestParam使用
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false));
// @RequestParam使用
resolvers.add(new RequestParamMapMethodArgumentResolver());
// @PathVariable使用
resolvers.add(new PathVariableMethodArgumentResolver());
// @PathVariable使用
resolvers.add(new PathVariableMapMethodArgumentResolver());
// @MatrixVariable使用(/cars;color=red;year=2012)
resolvers.add(new MatrixVariableMethodArgumentResolver());
// @MatrixVariable使用
resolvers.add(new MatrixVariableMapMethodArgumentResolver());
resolvers.add(new ServletModelAttributeMethodProcessor(false));
// 创建RequestResponseBodyMethodProcessor,并传入MessageConverters和requestResponseBodyAdvice
// requestResponseBodyAdvice中默认含有JsonViewResponseBodyAdvice、JsonViewRequestBodyAdvice
// 当然需要导入com.fasterxml.jackson的jar
// RequestBody和ResponseBody使用
resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
// @RequestPart上传文件使用
resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice));
resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));
resolvers.add(new RequestHeaderMapMethodArgumentResolver());
resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));
resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory()));
resolvers.add(new SessionAttributeMethodArgumentResolver());
resolvers.add(new RequestAttributeMethodArgumentResolver());
// Type-based argument resolution
resolvers.add(new ServletRequestMethodArgumentResolver());
resolvers.add(new ServletResponseMethodArgumentResolver());
resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
resolvers.add(new RedirectAttributesMethodArgumentResolver());
resolvers.add(new ModelMethodProcessor());
resolvers.add(new MapMethodProcessor());
resolvers.add(new ErrorsMethodArgumentResolver());
resolvers.add(new SessionStatusMethodArgumentResolver());
resolvers.add(new UriComponentsBuilderMethodArgumentResolver());
// Custom arguments
if (getCustomArgumentResolvers() != null) {
resolvers.addAll(getCustomArgumentResolvers());
}
// Catch-all
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true));
resolvers.add(new ServletModelAttributeMethodProcessor(true));
return resolvers;
}
RequestResponseBodyAdviceChain
class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyAdvice<Object> {
private final List<Object> requestBodyAdvice = new ArrayList<>(4);
private final List<Object> responseBodyAdvice = new ArrayList<>(4);
public RequestResponseBodyAdviceChain(@Nullable List<Object> requestResponseBodyAdvice) {
this.requestBodyAdvice.addAll(getAdviceByType(requestResponseBodyAdvice, RequestBodyAdvice.class));
this.responseBodyAdvice.addAll(getAdviceByType(requestResponseBodyAdvice, ResponseBodyAdvice.class));
}
}