spring提供了15种默认返回值处理器:
一、处理返回值:
this.returnValueHandlers.handleReturnValue( returnValue, getReturnValueType(returnValue), mavContainer, webRequest)
二、获取对应的返回值处理器:
private HandlerMethodReturnValueHandler selectHandler(@Nullable Object value, MethodParameter returnType) { boolean isAsyncValue = isAsyncReturnValue(value, returnType); //通过循环一个一个判断当前返回值处理器是否支持处理当前返回值 for (HandlerMethodReturnValueHandler handler : this.returnValueHandlers) { if (isAsyncValue && !(handler instanceof AsyncHandlerMethodReturnValueHandler)) { continue; } //是否支持处理当前返回值 if (handler.supportsReturnType(returnType)) { return handler; } } return null; }
三、根据返回的返回值处理器处理返回值:
if (handler == null) { throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName()); } //执行处理返回值 handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
扩展:返回值处理器接口:
HandlerMethodReturnValueHandler
public interface HandlerMethodReturnValueHandler { /** * 当前返回值处理器是否支持处理返回值 */ boolean supportsReturnType(MethodParameter returnType); /** * 处理当前返回值 */ void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception; }
二、内容协商
springmvc可以根据游览器可接受的内容和响应头接受的类型进行返回值协商:
①判断响应头是否有返回值要求:
MediaType selectedMediaType = null; MediaType contentType = outputMessage.getHeaders().getContentType(); boolean isContentTypePreset = contentType != null && contentType.isConcrete(); if (isContentTypePreset) { if (logger.isDebugEnabled()) { logger.debug("Found 'Content-Type:" + contentType + "' in response"); } selectedMediaType = contentType; }
②判断游览器支持的返回值类型:
2.1:获取游览器可接受的返回值类型。
2.2:服务器可生产的返回值类型。
HttpServletRequest request = inputMessage.getServletRequest(); ListacceptableTypes; try { //获取游览器支持的响应类型 acceptableTypes = getAcceptableMediaTypes(request); } catch (HttpMediaTypeNotAcceptableException ex) { int series = outputMessage.getServletResponse().getStatus() / 100; if (body == null || series == 4 || series == 5) { if (logger.isDebugEnabled()) { logger.debug("Ignoring error response content (if any). " + ex); } return; } throw ex; } //服务器可生产的返回值类型 List producibleTypes = getProducibleMediaTypes(request, valueType, targetType); if (body != null && producibleTypes.isEmpty()) { throw new HttpMessageNotWritableException( "No converter found for return value of type: " + valueType); } List mediaTypesToUse = new ArrayList<>(); //通过游览器可接受的类型和服务器可生产的类型进行匹配 for (MediaType requestedType : acceptableTypes) { for (MediaType producibleType : producibleTypes) { if (requestedType.isCompatibleWith(producibleType)) { mediaTypesToUse.add(getMostSpecificMediaType(requestedType, producibleType)); } } } if (mediaTypesToUse.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("No match for " + acceptableTypes + ", supported: " + producibleTypes); } if (body != null) { throw new HttpMediaTypeNotAcceptableException(producibleTypes); } return; } MediaType.sortBySpecificityAndQuality(mediaTypesToUse); //找到服务器可生产的类型以及游览器可接受的类型,双向同意 for (MediaType mediaType : mediaTypesToUse) { if (mediaType.isConcrete()) { selectedMediaType = mediaType; break; } else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) { selectedMediaType = MediaType.APPLICATION_OCTET_STREAM; break; } } if (logger.isDebugEnabled()) { logger.debug("Using '" + selectedMediaType + "', given " + acceptableTypes + " and supported " + producibleTypes); }
③进行内容转换(消息转换):
selectedMediaType = selectedMediaType.removeQualityValue();
//循环所有的消息转换器
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)) {
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 {
((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage);
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Nothing to write: null body");
}
}
return;
}
}
内容协商策略:
public ListresolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException { for (ContentNegotiationStrategy strategy : this.strategies) { List mediaTypes = strategy.resolveMediaTypes(request); if (mediaTypes.equals(MEDIA_TYPE_ALL_LIST)) { continue; } return mediaTypes; } return MEDIA_TYPE_ALL_LIST; }
默认是基于请求头的策略:
开启基于参数的内容协商策略:
spring: mvc: contentnegotiation: favor-parameter: true
通过url?format=xml....基于参与内容协商