1. HttpMessageConverter 概述
HttpMessageConverter 其實就是將 HttpServletRequest 中的數據, 根據 MediaType 轉換成指定格式的數據, 比如我們常見的表單提交 或通過 Json字符串提交數據, 其主要實現接口如下:
// 數據轉換器 -> 將數據轉換成 requests 或 response 中的數據
public interface HttpMessageConverter<T> {
// 指定的 class 是否支持讀取(MediaType 指數據的格式)
boolean canRead(Class<?> clazz, MediaType mediaType);
// 傳入 class 與 MediaType -> 看 HttpMessageConverter 是否支持寫數據到數據流中
boolean canWrite(Class<?> clazz, MediaType mediaType);
// 返回 HttpMessageConverter 支持的 MediaType
List<MediaType> getSupportedMediaTypes();
// 從 HttpInputMessage 中讀取數據流, 并轉化成 T 這站類型
T read(Class<? extends T> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
// 將 T 里面的數據信息寫入到 HttpOutputMessage 的數據流中
void write(T t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
}
對于接口的實現類主要有如下幾類:
1. FormHttpMessageConverter
支持 MultiValueMap 類型, 并且 MediaType 類型是 "multipart/form-data", 從 InputStream 里面讀取數據, 并通過&符號分割, 最后轉換成 MultiValueMap, 或 將 MultiValueMap轉換成 & 符號連接的字符串, 最后轉換成字節流, 輸出到遠端
2. BufferedImageHttpMessageConverter
支持 BufferedImgae 的 HttpMessageConverter, 通過 ImageReader 將 HttpBody 里面的數據轉換成 BufferedImage, 或ImageWriter 將ImageReader 轉換成字節流輸出到 OutputMessage
3. StringHttpMessageConverter
支持數據是 String 類型的, 從 InputMessage 中讀取指定格式的 str, 或 將數據編碼成指定的格式輸出到 OutputMessage
4. SourceHttpMessageConverter
支持 DOMSource, SAXSource, StAXSource, StreamSource, Source 類型的消息轉換器, 在讀取的時候, 從 HttpBody 里面讀取對應的數據流轉換成對應對應, 輸出時通過 TransformerFactory 轉換成指定格式輸出
5. ResourceHttpMessageConverter
支持數據類型是 Resource 的數據, 從 HttpBody 中讀取數據流轉換成 InputStreamResource|ByteArrayResource, 或從 Resource 中讀取數據流, 輸出到遠端
6. ProtobufHttpMessageConverter
支持數據類型是 com.google.protobuf.Message, 通過 com.google.protobuf.Message.Builder 將 HttpBody 中的數據流轉換成指定格式的 Message, 通過 ProtobufFormatter 將 com.google.protobuf.Message 轉換成字節流輸出到遠端
7. ObjectToStringHttpMessageConverter
支持 MediaType是 text/plain 類型, 從 InputMessage 讀取數據轉換成字符串, 通過 ConversionService 將字符串轉換成自定類型的 Object; 或將 Obj 轉換成 String, 最后 將 String 轉換成數據流
8. ByteArrayHttpMessageConverter
支持格式是 byte 類型, 從 InputMessage 中讀取指定長度的字節流, 或將 OutputMessage 轉換成字節流
9. AbstractXmlHttpMessageConverter及其子類
支持從 xml 與 Object 之間進行數據轉換的 HttpMessageConverter
10. AbstractGenericHttpMessageConverter
支持從 Json 與 Object 之間進行數據轉換的 HttpMessageConverter (PS: 主要通過 JackSon 或 Gson)
11. GsonHttpMessageConverter
支持 application/*++json 格式的數據, 并通過 Gson, 將字符串轉換成對應的數據
12. MappingJackson2XmlHttpMessageConverter
持 application/*++json/*+xml 格式的數據, 并通過 JackSon, 將字符串轉換成對應的數據
2. HttpMessageConverter 總結
HttpMessageConverter 在整個 SpringMVC 中起著根據 MediaType 類型將 HttpServletRequest 中的數據轉換成 指定對象的轉換器, 或將對象轉換成指定格式的數據(PS: byte/String/xml/json 等); 在其整體設計上與 HandlerMethodArgumentResolver 相似!