認識HttpMessageConverter

DispatcherServlet默認裝配一下幾個HandlerAdapters

org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter
org.springframework.web.HttpRequestHandler
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

RequestMappingHandlerAdapter中默認裝載瞭如下幾個HttpMessageConverterjava

public RequestMappingHandlerAdapter() {
   StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
   stringHttpMessageConverter.setWriteAcceptCharset(false);  // see SPR-7316

   this.messageConverters = new ArrayList<>(4);
   this.messageConverters.add(new ByteArrayHttpMessageConverter());
   this.messageConverters.add(stringHttpMessageConverter);
   this.messageConverters.add(new SourceHttpMessageConverter<>());
   this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}

 

項目中加入Jackson依賴後,還會加載 MappingJackson2HttpMessageConverter.web

注意:spring-web依賴包中是有MappingJackson2HttpMessageConverter類的spring

本文重點:

@RequestBody、@ResponseBody註解,能夠直接將輸入解析成Json、將輸出解析成Json,但HTTP 請求和響應是基於文本的,意味着瀏覽器和服務器經過交換原始文本進行通訊,而這裏其實就是HttpMessageConverter發揮着做用。json

 

HttpMessageConverter接口的源碼以下:瀏覽器

public interface HttpMessageConverter<T> {

	
	boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

	
	boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

	
	List<MediaType> getSupportedMediaTypes();

	T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException;

	void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException;

}

 

運行順序

1.只有當處理器方法使用到 @RequestBody/@ResponseBody 或HttpEntity<T>/ResponseEntity<T> 時,SpringMVC才使用註冊的HttpMessageConverter 對請求響應消息進行處理。服務器

2.當控制器處理方法使用到 @RequestBody/@ResponseBody 或HttpEntity<T>/ResponseEntity<T> 時,Spring 首先根據請求頭或響應頭的 Accept 屬性選擇匹配的 HttpMessageConverter, 而後根據參數類型或泛型類型的過濾獲得匹配的 HttpMessageConverter, 若找不到可用的 HttpMessageConverter 將報錯mvc

3.@RequestBody 和 @ResponseBody 不須要成對出現。若是方法入參使用到了@RequestBody,SpringMVC將會選擇匹配的HttpMessageConverter 將請求信息轉換並綁定到該入參中。若是處理方法標註了@ResponseBody,SpringMVC選擇匹配的HttpMessageConverter 將方法返回值轉換並輸出響應消息。app

替換默認的MappingJackson2HttpMessageConverter

SpringBoot中,使用FastJsonHttpMessageConverter替換默認的MappingJackson2HttpMessageConverter。this

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;

import java.nio.charset.Charset;

@Configuration
public class HttpMessageConverterConfig {
    /**
     * 引入Fastjson解析json,不使用默認的jackson
     * 必須在pom.xml引入fastjson的jar包,而且版必須大於1.2.10
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //一、定義一個convert轉換消息的對象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //二、添加fastjson的配置信息
        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        SerializerFeature[] serializerFeatures = new SerializerFeature[]{
                //    輸出key是包含雙引號
//                SerializerFeature.QuoteFieldNames,
                //    是否輸出爲null的字段,若爲null 則顯示該字段
//                SerializerFeature.WriteMapNullValue,
                //    數值字段若是爲null,則輸出爲0
                SerializerFeature.WriteNullNumberAsZero,
                //     List字段若是爲null,輸出爲[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                //    字符類型字段若是爲null,輸出爲"",而非null
                SerializerFeature.WriteNullStringAsEmpty,
                //    Boolean字段若是爲null,輸出爲false,而非null
                SerializerFeature.WriteNullBooleanAsFalse,
                //    Date的日期轉換器
                SerializerFeature.WriteDateUseDateFormat,
                //    循環引用
                SerializerFeature.DisableCircularReferenceDetect,
        };

        fastJsonConfig.setSerializerFeatures(serializerFeatures);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));

        //三、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);

        //四、將convert添加到converters中
        HttpMessageConverter<?> converter = fastConverter;

        return new HttpMessageConverters(converter);
    }

}
相關文章
相關標籤/搜索