关于json,xml的自动转换原理的核心就在messageConvert,前一篇我们已经分析到通过messageConvert对请求参数进行解析读取,那就续点分析。
本节就以json的转换为例(xml类同只是不同的messageConvert)来进行分析,在我们对请求参数解析时候回顾下readWithMessageConverters方法
body = ((HttpMessageConverter<T>) converter).read(targetClass, inputMessage);
通过converter读取请求消息
那么问题来了,这些messageConverts哪来的呢?
我们知道RequestMappingHandlerAdapter是请求处理的适配器,也就是请求之后处理具体逻辑的执行,关系到哪个类的哪个方法以及转换器等工作,这个类是我们讲的重点,其中它的属性messageConverters就是我们关注的重点
RequestMappingHandlerAdapter有个默认构造函数
public RequestMappingHandlerAdapter() { StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316 this.messageConverters = new ArrayList<HttpMessageConverter<?>>(4); this.messageConverters.add(new ByteArrayHttpMessageConverter()); this.messageConverters.add(stringHttpMessageConverter); this.messageConverters.add(new SourceHttpMessageConverter<Source>()); this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); }很明显在创建对象实例的时候 就对messageConverters进行了赋值,最后添加的AllEncompassingFormHttpMessageConverter 所有包含的FormHttpMessageConverter,看看究竟有哪些
if条件的值 则是
private static final boolean jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", AllEncompassingFormHttpMessageConverter.class.getClassLoader()); private static final boolean jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", AllEncompassingFormHttpMessageConverter.class.getClassLoader()); private static final boolean jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", AllEncompassingFormHttpMessageConverter.class.getClassLoader()); private static final boolean gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", AllEncompassingFormHttpMessageConverter.class.getClassLoader());
也就是当com.fasterxml.jackson.databind.ObjectMapper和com.fasterxml.jackson.core.JsonGenerator存在在classpath中才会去加载MappingJackson2HttpMessageConverter。(其他一样的道理)
现在是不是知道了 为什么 springMVC默认就支持json转换器,不过这里我用fastjson作为分析例子
messageConverter的read方法
public final T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException { return readInternal(clazz, inputMessage); }FastJsonHttpMessageConverter的readInternal方法为:
protected Object readInternal(Class<? extends Object> clazz, // HttpInputMessage inputMessage // ) throws IOException, HttpMessageNotReadableException { InputStream in = inputMessage.getBody(); return JSON.parseObject(in, fastJsonConfig.getCharset(), clazz, fastJsonConfig.getFeatures()); }可以看到就是把请求消息体输入流转换为json对象,这就是整个消息转化为json的过程
下面我们解析分析 是如何将@ResponseBody注解标准的Controller方法返回的java对象转换为json的
还记得之前RequestMappingHandlerAdapter中invokeAndHandle方法么,其中也包含了对返回值的处理
this.returnValueHandlers.handleReturnValue( returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
handleReturnValule方法的具体实现:
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { HandlerMethodReturnValueHandler handler = selectHandler(returnValue, returnType); if (handler == null) { throw new IllegalArgumentException("Unknown return value type: " + returnType.getParameterType().getName()); } handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest); }首先通过返回值以及返回类型搜索对应的returnValueHandler,其次再通过得到的handler对返回消息进行处理
handleRreturnValue的实现为
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException { mavContainer.setRequestHandled(true); // Try even with null return value. ResponseBodyAdvice could get involved. writeWithMessageConverters(returnValue, returnType, webRequest); }没有似曾相识的感觉 之前我们分析解析请求消息时候 有个readWithMessageConverters 现在又有个writeWithMessageConverters方法,那我们看看具体实现:
方法中代码太多,中间一段略过。。。。。
write方法是代码如下:
public final void write(final T t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { final HttpHeaders headers = outputMessage.getHeaders(); addDefaultHeaders(headers, t, contentType); if (outputMessage instanceof StreamingHttpOutputMessage) { StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage; streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() { @Override public void writeTo(final OutputStream outputStream) throws IOException { writeInternal(t, new HttpOutputMessage() { @Override public OutputStream getBody() throws IOException { return outputStream; } @Override public HttpHeaders getHeaders() { return headers; } }); } }); } else { writeInternal(t, outputMessage); outputMessage.getBody().flush(); } }我们重点关注writeInternal方法的实现,在FastJsonHttpMessageConverter中为
protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { HttpHeaders headers = outputMessage.getHeaders(); ByteArrayOutputStream outnew = new ByteArrayOutputStream(); boolean writeAsToString = false; if (obj != null) { String className = obj.getClass().getName(); if ("com.fasterxml.jackson.databind.node.ObjectNode".equals(className)) { writeAsToString = true; } } if (writeAsToString) { String text = obj.toString(); OutputStream out = outputMessage.getBody(); out.write(text.getBytes()); if (fastJsonConfig.isWriteContentLength()) { headers.setContentLength(text.length()); } } else { int len = JSON.writeJSONString(outnew, // fastJsonConfig.getCharset(), // obj, // fastJsonConfig.getSerializeConfig(), // fastJsonConfig.getSerializeFilters(), // fastJsonConfig.getDateFormat(), // JSON.DEFAULT_GENERATE_FEATURE, // fastJsonConfig.getSerializerFeatures()); if (fastJsonConfig.isWriteContentLength()) { headers.setContentLength(len); } OutputStream out = outputMessage.getBody(); outnew.writeTo(out); } outnew.close(); }
此方法中将Java对象转换为json字符串
其他消息转换器类似,如果读者感兴趣可自己去查看代码研究,这里就不作分析拉