SpringMVC源碼總結(七)mvc:annotation-driven中的HttpMessageConverter

這一篇文章主要介紹下HttpMessageConverter整個註冊過程包含自定義的HttpMessageConverter,然後對一些HttpMessageConverter進行具體介紹。 

HttpMessageConverter接口介紹:
 
Java代碼  收藏代碼
  1. public interface HttpMessageConverter<T> {  
  2.   
  3.     /** 
  4.      * Indicates whether the given class can be read by this converter. 
  5.      * @param clazz the class to test for readability 
  6.      * @param mediaType the media type to read, can be {@code null} if not specified. 
  7.      * Typically the value of a {@code Content-Type} header. 
  8.      * @return {@code true} if readable; {@code false} otherwise 
  9.      */  
  10.     boolean canRead(Class<?> clazz, MediaType mediaType);  
  11.   
  12.     /** 
  13.      * Indicates whether the given class can be written by this converter. 
  14.      * @param clazz the class to test for writability 
  15.      * @param mediaType the media type to write, can be {@code null} if not specified. 
  16.      * Typically the value of an {@code Accept} header. 
  17.      * @return {@code true} if writable; {@code false} otherwise 
  18.      */  
  19.     boolean canWrite(Class<?> clazz, MediaType mediaType);  
  20.   
  21.     /** 
  22.      * Return the list of {@link MediaType} objects supported by this converter. 
  23.      * @return the list of supported media types 
  24.      */  
  25.     List<MediaType> getSupportedMediaTypes();  
  26.   
  27.     /** 
  28.      * Read an object of the given type form the given input message, and returns it. 
  29.      * @param clazz the type of object to return. This type must have previously been passed to the 
  30.      * {@link #canRead canRead} method of this interface, which must have returned {@code true}. 
  31.      * @param inputMessage the HTTP input message to read from 
  32.      * @return the converted object 
  33.      * @throws IOException in case of I/O errors 
  34.      * @throws HttpMessageNotReadableException in case of conversion errors 
  35.      */  
  36.     T read(Class<? extends T> clazz, HttpInputMessage inputMessage)  
  37.             throws IOException, HttpMessageNotReadableException;  
  38.   
  39.     /** 
  40.      * Write an given object to the given output message. 
  41.      * @param t the object to write to the output message. The type of this object must have previously been 
  42.      * passed to the {@link #canWrite canWrite} method of this interface, which must have returned {@code true}. 
  43.      * @param contentType the content type to use when writing. May be {@code null} to indicate that the 
  44.      * default content type of the converter must be used. If not {@code null}, this media type must have 
  45.      * previously been passed to the {@link #canWrite canWrite} method of this interface, which must have 
  46.      * returned {@code true}. 
  47.      * @param outputMessage the message to write to 
  48.      * @throws IOException in case of I/O errors 
  49.      * @throws HttpMessageNotWritableException in case of conversion errors 
  50.      */  
  51.     void write(T t, MediaType contentType, HttpOutputMessage outputMessage)  
  52.             throws IOException, HttpMessageNotWritableException;  
  53.   
  54. }  

從HttpInputMessage中讀取數據: T read(Class<? extends T> clazz, HttpInputMessage inputMessage),前提clazz能夠通過canRead(clazz,mediaType)測試。 
向HttpOutputMessage中寫入數據:void write(T t, MediaType contentType, HttpOutputMessage outputMessage),前提能夠通過canWrite方法。 

簡單舉例: 
如StringHttpMessageConverter,read方法就是根據編碼類型將HttpInputMessage中的數據變爲字符串。write方法就是根據編碼類型將字符串數據寫入HttpOutputMessage中。 

HttpMessageConverter的使用場景: 
它主要是用來轉換request的內容到一定的格式,轉換輸出的內容的到response。 
看下自定義的使用方式:
 
Java代碼  收藏代碼
  1. <mvc:annotation-driven>  
  2.         <mvc:message-converters register-defaults="true">  
  3.             <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
  4.                 <constructor-arg value="UTF-8"/>  
  5.             </bean>  
  6.         </mvc:message-converters>  
  7.     </mvc:annotation-driven>  

首先還是在對mvc:annotation-driven解析的AnnotationDrivenBeanDefinitionParser中,有這麼一個方法: 
Java代碼  收藏代碼
  1. ManagedList<?> messageConverters = getMessageConverters(element, source, parserContext);  

獲取所有的HttpMessageConverter,最終設置到RequestMappingHandlerAdapter的private List<HttpMessageConverter<?>> messageConverters屬性上。看下具體的獲取過程: 
Java代碼  收藏代碼
  1. private ManagedList<?> getMessageConverters(Element element, Object source, ParserContext parserContext) {  
  2.         Element convertersElement = DomUtils.getChildElementByTagName(element, "message-converters");  
  3.         ManagedList<? super Object> messageConverters = new ManagedList<Object>();  
  4.         if (convertersElement != null) {  
  5.             messageConverters.setSource(source);  
  6.             for (Element beanElement : DomUtils.getChildElementsByTagName(convertersElement, "bean""ref")) {  
  7.                 Object object = parserContext.getDelegate().parsePropertySubElement(beanElement, null);  
  8.                 messageConverters.add(object);  
  9.             }  
  10.         }  
  11.   
  12.         if (convertersElement == null || Boolean.valueOf(convertersElement.getAttribute("register-defaults"))) {  
  13.             messageConverters.setSource(source);  
  14.             messageConverters.add(createConverterDefinition(ByteArrayHttpMessageConverter.class, source));  
  15.   
  16.             RootBeanDefinition stringConverterDef = createConverterDefinition(StringHttpMessageConverter.class, source);  
  17.             stringConverterDef.getPropertyValues().add("writeAcceptCharset"false);  
  18.             messageConverters.add(stringConverterDef);  
  19.   
  20.             messageConverters.add(createConverterDefinition(ResourceHttpMessageConverter.class, source));  
  21.             messageConverters.add(createConverterDefinition(SourceHttpMessageConverter.class, source));  
  22.             messageConverters.add(createConverterDefinition(AllEncompassingFormHttpMessageConverter.class, source));  
  23.   
  24.             if (romePresent) {  
  25.                 messageConverters.add(createConverterDefinition(AtomFeedHttpMessageConverter.class, source));  
  26.                 messageConverters.add(createConverterDefinition(RssChannelHttpMessageConverter.class, source));  
  27.             }  
  28.             if (jaxb2Present) {  
  29.                 messageConverters.add(createConverterDefinition(Jaxb2RootElementHttpMessageConverter.class, source));  
  30.             }  
  31.             if (jackson2Present) {  
  32.                 messageConverters.add(createConverterDefinition(MappingJackson2HttpMessageConverter.class, source));  
  33.             }  
  34.             else if (jacksonPresent) {  
  35.                 messageConverters.add(createConverterDefinition(  
  36.                         org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.class, source));  
  37.             }  
  38.         }  
  39.         return messageConverters;  
  40.     }  

該過程第一步: 
解析並獲取我們自定義的HttpMessageConverter, 
該過程第二步: 
<mvc:message-converters register-defaults="true">有一個register-defaults屬性,當爲true時,仍然註冊默認的HttpMessageConverter,當爲false則不註冊,僅僅使用用戶自定義的HttpMessageConverter。 

獲取完畢,便會將這些HttpMessageConverter設置進RequestMappingHandlerAdapter的messageConverters屬性中。 

然後就是它的使用過程,HttpMessageConverter主要針對那些不會返回view視圖的response: 
即含有方法含有@ResponseBody或者返回值爲HttpEntity等類型的,它們都會用到HttpMessageConverter。以@ResponseBody舉例: 
首先先決定由哪個HandlerMethodReturnValueHandler來處理返回值,由於是@ResponseBody所以將會由RequestResponseBodyMethodProcessor來處理,然後就是如下的寫入:
 
Java代碼  收藏代碼
  1. protected <T> void writeWithMessageConverters(T returnValue, MethodParameter returnType,  
  2.             ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage)  
  3.             throws IOException, HttpMediaTypeNotAcceptableException {  
  4.   
  5.         Class<?> returnValueClass = returnValue.getClass();  
  6.         HttpServletRequest servletRequest = inputMessage.getServletRequest();  
  7.         List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(servletRequest);  
  8.         List<MediaType> producibleMediaTypes = getProducibleMediaTypes(servletRequest, returnValueClass);  
  9.   
  10.         Set<MediaType> compatibleMediaTypes = new LinkedHashSet<MediaType>();  
  11.         for (MediaType requestedType : requestedMediaTypes) {  
  12.             for (MediaType producibleType : producibleMediaTypes) {  
  13.                 if (requestedType.isCompatibleWith(producibleType)) {  
  14.                     compatibleMediaTypes.add(getMostSpecificMediaType(requestedType, producibleType));  
  15.                 }  
  16.             }  
  17.         }  
  18.         if (compatibleMediaTypes.isEmpty()) {  
  19.             throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes);  
  20.         }  
  21.   
  22.         List<MediaType> mediaTypes = new ArrayList<MediaType>(compatibleMediaTypes);  
  23.         MediaType.sortBySpecificityAndQuality(mediaTypes);  
  24.   
  25.         MediaType selectedMediaType = null;  
  26.         for (MediaType mediaType : mediaTypes) {  
  27.             if (mediaType.isConcrete()) {  
  28.                 selectedMediaType = mediaType;  
  29.                 break;  
  30.             }  
  31.             else if (mediaType.equals(MediaType.ALL) || mediaType.equals(MEDIA_TYPE_APPLICATION)) {  
  32.                 selectedMediaType = MediaType.APPLICATION_OCTET_STREAM;  
  33.                 break;  
  34.             }  
  35.         }  
  36.   
  37.         if (selectedMediaType != null) {  
  38.             selectedMediaType = selectedMediaType.removeQualityValue();  
  39.             for (HttpMessageConverter<?> messageConverter : this.messageConverters) {  
  40.                 if (messageConverter.canWrite(returnValueClass, selectedMediaType)) {  
  41.                     ((HttpMessageConverter<T>) messageConverter).write(returnValue, selectedMediaType, outputMessage);  
  42.                     if (logger.isDebugEnabled()) {  
  43.                         logger.debug("Written [" + returnValue + "] as \"" + selectedMediaType + "\" using [" +  
  44.                                 messageConverter + "]");  
  45.                     }  
  46.                     return;  
  47.                 }  
  48.             }  
  49.         }  
  50.         throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);  
  51.     }  

選取一個合適的content-type,再由這個content-type和返回類型來選取合適的HttpMessageConverter,找到合適的HttpMessageConverter後,便調用它的write方法。 

接下來就說一說一些具體的HttpMessageConverter。 

AbstractHttpMessageConverter:提供了進一步的抽象,將是否支持相應的MediaType這一共有的功能實現,它的子類只需關心是否支持返回類型。 

AbstractHttpMessageConverter子類-StringHttpMessageConverter:如用於處理字符串到response中,這就要涉及編碼問題,這一過程在本系列的第四篇文章中做過詳細說明,這裏跳過。 

AbstractHttpMessageConverter子類-ByteArrayHttpMessageConverter:
 
Java代碼  收藏代碼
  1. public class ByteArrayHttpMessageConverter extends AbstractHttpMessageConverter<byte[]> {  
  2.   
  3.     /** Creates a new instance of the {@code ByteArrayHttpMessageConverter}. */  
  4.     public ByteArrayHttpMessageConverter() {  
  5.         super(new MediaType("application""octet-stream"), MediaType.ALL);  
  6.     }  
  7.   
  8.     @Override  
  9.     public boolean supports(Class<?> clazz) {  
  10.         return byte[].class.equals(clazz);  
  11.     }  
  12.   
  13.     @Override  
  14.     public byte[] readInternal(Class<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException {  
  15.         long contentLength = inputMessage.getHeaders().getContentLength();  
  16.         ByteArrayOutputStream bos =  
  17.                 new ByteArrayOutputStream(contentLength >= 0 ? (int) contentLength : StreamUtils.BUFFER_SIZE);  
  18.         StreamUtils.copy(inputMessage.getBody(), bos);  
  19.         return bos.toByteArray();  
  20.     }  
  21.   
  22.     @Override  
  23.     protected Long getContentLength(byte[] bytes, MediaType contentType) {  
  24.         return (long) bytes.length;  
  25.     }  
  26.   
  27.     @Override  
  28.     protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException {  
  29.         StreamUtils.copy(bytes, outputMessage.getBody());  
  30.     }  
  31.   
  32. }  

源碼就很清晰明瞭。它專門負責byte[]類型的轉換。 

AbstractHttpMessageConverter子類-MappingJacksonHttpMessageConverter:用於轉換Object到json字符串類型。已過時,使用的是http://jackson.codehaus.org中Jackson 1.x的ObjectMapper,取代者爲MappingJackson2HttpMessageConverter。依賴爲:
 
Java代碼  收藏代碼
  1. <dependency>   
  2.         <groupId>org.codehaus.jackson</groupId>   
  3.         <artifactId>jackson-core-asl</artifactId>   
  4.         <version>1.9.11</version>   
  5.     </dependency>   
  6.       
  7.     <dependency>   
  8.         <groupId>org.codehaus.jackson</groupId>   
  9.         <artifactId>jackson-mapper-asl</artifactId>   
  10.         <version>1.9.11</version>   
  11.     </dependency>   
  12.       

AbstractHttpMessageConverter子類-MappingJackson2HttpMessageConverter: 
它所使用的json轉換器是http://jackson.codehaus.org中Jackson 2.x的ObjectMapper。 
依賴的jar包爲有3個,jackson-databind和它的兩個依賴jackson-annotations、jackson-core,但是有了jackson-databind的pom文件會去自動下載它的依賴,所以只需增添jackson-databind的pom即可獲取上述3個jar包:
 
Java代碼  收藏代碼
  1. <dependency>  
  2.     <dependency>  
  3.         <groupId>com.fasterxml.jackson.core</groupId>  
  4.         <artifactId>jackson-databind</artifactId>  
  5.         <version>2.4.2</version>   
  6.     </dependency>  

接下來便說道:在註冊HttpMessageConverter過程中的一些問題: 
Java代碼  收藏代碼
  1. if (convertersElement == null || Boolean.valueOf(convertersElement.getAttribute("register-defaults"))) {  
  2.             messageConverters.setSource(source);  
  3.             messageConverters.add(createConverterDefinition(ByteArrayHttpMessageConverter.class, source));  
  4.   
  5.             RootBeanDefinition stringConverterDef = createConverterDefinition(StringHttpMessageConverter.class, source);  
  6.             stringConverterDef.getPropertyValues().add("writeAcceptCharset"false);  
  7.             messageConverters.add(stringConverterDef);  
  8.   
  9.             messageConverters.add(createConverterDefinition(ResourceHttpMessageConverter.class, source));  
  10.             messageConverters.add(createConverterDefinition(SourceHttpMessageConverter.class, source));  
  11.             messageConverters.add(createConverterDefinition(AllEncompassingFormHttpMessageConverter.class, source));  
  12.   
  13.             if (romePresent) {  
  14.                 messageConverters.add(createConverterDefinition(AtomFeedHttpMessageConverter.class, source));  
  15.                 messageConverters.add(createConverterDefinition(RssChannelHttpMessageConverter.class, source));  
  16.             }  
  17.             if (jaxb2Present) {  
  18.                 messageConverters.add(createConverterDefinition(Jaxb2RootElementHttpMessageConverter.class, source));  
  19.             }  
  20.             if (jackson2Present) {  
  21.                 messageConverters.add(createConverterDefinition(MappingJackson2HttpMessageConverter.class, source));  
  22.             }  
  23.             else if (jacksonPresent) {  
  24.                 messageConverters.add(createConverterDefinition(  
  25.                         org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.class, source));  
  26.             }  
  27.         }  

這段代碼是在註冊默認的HttpMessageConverter,但是個別HttpMessageConverter也是有條件的。即相應的jar包存在,纔會去註冊它。如MappingJackson2HttpMessageConverter,if (jackson2Present) { 
messageConverters.add(createConverterDefinition(MappingJackson2HttpMessageConverter.class, source));當jackson2Present爲true時纔會註冊。而jackson2Present的值如下:
 
Java代碼  收藏代碼
  1. private static final boolean jackson2Present =  
  2.             ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", AnnotationDrivenBeanDefinitionParser.class.getClassLoader()) &&  
  3.                     ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());  

也就是當com.fasterxml.jackson.databind.ObjectMapper和com.fasterxml.jackson.core.JsonGenerator存在在classpath中才會去加載MappingJackson2HttpMessageConverter。 

同理,MappingJacksonHttpMessageConverter的判斷如下:
 
Java代碼  收藏代碼
  1. private static final boolean jacksonPresent =  
  2.             ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", AnnotationDrivenBeanDefinitionParser.class.getClassLoader()) &&  
  3.                     ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", AnnotationDrivenBeanDefinitionParser.class.getClassLoader());  


所以當我們程序沒法轉換json時,你就需要考慮是否已經把MappingJacksonHttpMessageConverter或者MappingJackson2HttpMessageConverter的依賴加進來了,官方推薦使用MappingJackson2HttpMessageConverter。

轉載自:http://blog.csdn.net/z69183787/article/details/52817067

發佈了3 篇原創文章 · 獲贊 16 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章