將請求封包轉換為Java物件
將Java物件轉換為回應訊息
getSupportedMediaTypes:取得支援的MediaType集合(如:text/html,text/plain,application/json)
canRead:判斷是否能讀取(請求)
#read:將請求資料進行格式轉換(canRead方法傳回值為true時調用)
canWrite:判斷是否能寫入(回應)
#write:將回應資料進行格式轉換(canWrite方法傳回值為true時呼叫)
SpringMVC啟動時會自動配置一些HttpMessageConverter(WebMvcConfigurationSupport類別的addDefaultHttpMessageConverters)方法
##來源碼如下:protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) { messageConverters.add(new ByteArrayHttpMessageConverter()); messageConverters.add(new StringHttpMessageConverter()); messageConverters.add(new ResourceHttpMessageConverter()); messageConverters.add(new ResourceRegionHttpMessageConverter()); try { messageConverters.add(new SourceHttpMessageConverter<>()); } catch (Throwable ex) { // Ignore when no TransformerFactory implementation is available... } messageConverters.add(new AllEncompassingFormHttpMessageConverter()); if (romePresent) { messageConverters.add(new AtomFeedHttpMessageConverter()); messageConverters.add(new RssChannelHttpMessageConverter()); } if (jackson2XmlPresent) { Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml(); if (this.applicationContext != null) { builder.applicationContext(this.applicationContext); } messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.build())); } else if (jaxb2Present) { messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); } if (jackson2Present) { Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json(); if (this.applicationContext != null) { builder.applicationContext(this.applicationContext); } messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build())); } else if (gsonPresent) { messageConverters.add(new GsonHttpMessageConverter()); } else if (jsonbPresent) { messageConverters.add(new JsonbHttpMessageConverter()); } if (jackson2SmilePresent) { Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.smile(); if (this.applicationContext != null) { builder.applicationContext(this.applicationContext); } messageConverters.add(new MappingJackson2SmileHttpMessageConverter(builder.build())); } if (jackson2CborPresent) { Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.cbor(); if (this.applicationContext != null) { builder.applicationContext(this.applicationContext); } messageConverters.add(new MappingJackson2CborHttpMessageConverter(builder.build())); } }部分訊息轉換器解析
描述 | |
---|---|
負責讀取、寫JSON格式資料(利用Jackson) | |
#負責讀取、寫入Form表單資料 | |
負責讀取、寫入XML格式資料(使用JAXB) | |
#ByteArrayHttpMessageConverter | |
StringHttpMessageConverter |
以上是SpringBoot HttpMessageConverter訊息轉換器如何使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!