认识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);
    }

}
相关文章
相关标签/搜索