ResponseBody注解

用在Controller的方法的返回对象上, 通过httpmessageconverter转换为指定格式。再写到responser body数据区,

和Request header中的accept配合,可以将java对象转为对应的xml或者json

以下的例子是将Map对象转化为json

@RequestMapping("/requestBody")
public void requestBody(@RequestBody String body, Writer writer) throws IOException{
    writer.write(body);
}

@RequestMapping(value="/responseBody", produces="application/json")
@ResponseBody
public Map<String, Object> responseBody(){
    Map<String, Object> retMap = new HashMap<>();
    retMap.put("param1", "abc");
    return retMap;
}

RequestBody注解

根据类型把http请求体转化为指定的类弄,如上面demo中,是将http请求体转化为String对象。

HttpMessageConverter

HttpMessageConverter 做为中转,把请求的报文进行字符串到对象的转化,以及对象再到字符串的转化。

RequestBody 会根据入参数类型,选择对应 的httpMessageConverter来解析,如果是字符串类型就用StringHttpMessage来转化,

返回的时候 ,ResponseBody用StringHttpMessageConverter的write() 方法 将结果写入响应报文。

该接口下面包含五个方法,如下

public interface HttpMessageConverter<T> {

    // 当前转换器是否能将HTTP报文转换为对象类型
    boolean canRead(Class<?> clazz, MediaType mediaType);

    // 当前转换器是否能将对象类型转换为HTTP报文
    boolean canWrite(Class<?> clazz, MediaType mediaType);

    // 转换器能支持的HTTP媒体类型
    List<MediaType> getSupportedMediaTypes();

    // 转换HTTP报文为特定类型
    T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException;

    // 将特定类型对象转换为HTTP报文
    void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException;

}

在springboot或者spring mvc中,如果要转化为json格式的数据, @responsebody注解默认用的是jackson来解析json.

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.web.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() {
        //1、定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        //2、添加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"));

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

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

        return new HttpMessageConverters(converter);
    }
}

fastjson与jackson的不同之处在于,

如果是字符串类型的是null则返加“”

如果是数值类型的null则返加0

参考:

  1. https://jingyan.baidu.com/article/a24b33cd3c841319fe002b8a.html
  2. 原理参考:https://www.cnblogs.com/java-chen-hao/p/11187914.html
  3. HttpMessageConverter的作用及替换 https://www.jianshu.com/p/333ed5ee958d

本文由 hcb 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论