【SpringBoot】内容协商机制

问题提出: 浏览器收请求是 JSON—— 安卓客户端接收的请求是XML,难道这种时候我们只能重新写方法嘛?
回答: SpringBoot的内容协商机制可以解决这个问题。

背景知识:

JSON:
JSON全称为JavaScript Object Notation, 是一种语法,用来序列化对象、数组、数值、字符串、布尔值和 null 。它基于 JavaScript 语法,但与之不同:JavaScript 不是 JSON,JSON 也不是 JavaScript。
XML:
XML全称为eXtensible Markup Language(可扩展标记语言),是由 W3C 指定的一种通用标记语言。信息技术(IT)行业使用许多基于 XML 的语言作为数据描述性语言。XML 标签 类似 HTML 标签,但由于 XML 允许用户定义他们自己的标签,所以 XML 更加灵活。从这个层面来看,XML 表现的像一种元语言——也就是说,它可以被用来定义其他语言,例如 RSS。不仅如此,HTML 是陈述性语言,而 XML 是数据描述性语言。这意味着 XML 除了 Web 之外有更远更广的应用。例如,Web 服务可以利用 XML 去交换请求和响应。

一、内容协商:

1. 定义

根据不同客户端接受能力的不同,返回不同类型的数据。

2. 做个小实验 —— 使服务器返回XML格式数据

步骤一:导入XML解析模块
( 注意刚导入会标红,很正常,我们Roload一下项目即可
—— 步骤:鼠标右键点击项目名 —— MAVEN —— Reload )

 	<!--导入支持XML解析的模块-->
	 <dependency>
	     <groupId>com.fasterxml.jackson.dataformat</groupId>
	     <artifactId>jackson-dataformat-xml</artifactId>
	 </dependency>

步骤二:导入该模块后,我们再去访问之前的请求
结果返回的就是XML类型的数据了
—— 这时浏览器请求标头可接受的数据类型中,xml所占的权重(q值)更大
步骤三:查看请求标头 —— 请求标头如下:

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9

在这里插入图片描述

通俗的讲: 服务器发送什么请求,要看浏览器的 Accept字段 是什么,通过改变 Accept字段改变响应类型。Accept 字段即 HTTP 协议中规定的告诉服务器本客户端能接受什么样的数据类型。

二、内容协商原理 —— 源码分析

1. 从AbstractMessageConverterMethodProcessor.class开始

  1. 判断是否之前进行过处理,被写死了内容类型:即MediaType是否被写死(AbstractMessageConverterMethodProcessor.class)
 MediaType contentType = outputMessage.getHeaders().getContentType();
  1. 获取可接受的数据类型,即客户端支持的内容类型(AbstractMessageConverterMethodProcessor.class)
    ——(不妨Step Into 进去看看如何获取~~~)
List<MediaType> acceptableTypes = this.getAcceptableMediaTypes(request);

(1)用内容协商管理器解析媒体类型 —— 继续Step Into,看看如何解析

return this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request));

(2)使用请求头的响应类型,解析响应类型(ContentNegotiationManager.class)

ContentNegotiationStrategy strategy = (ContentNegotiationStrategy)var2.next();
mediaTypes = strategy.resolveMediaTypes(request);

(3)通过 getHeaderValues 得到请求(HeaderContentNegotiationStrategy.class)

  public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
       Iterator var2 = this.strategies.iterator();

       List mediaTypes;
       do {
           if (!var2.hasNext()) {
               return MEDIA_TYPE_ALL_LIST;
           }

           ContentNegotiationStrategy strategy = (ContentNegotiationStrategy)var2.next();
           mediaTypes = strategy.resolveMediaTypes(request);
       } while(mediaTypes.equals(MEDIA_TYPE_ALL_LIST));

       return mediaTypes;
   }

可接受的数据类型:

在这里插入图片描述

 String[] headerValueArray = request.getHeaderValues("Accept");
  1. 获取可产生的媒体类型
List<MediaType> producibleTypes = this.getProducibleMediaTypes(request, valueType, (Type)targetType);

可产生的数据类型:

在这里插入图片描述

  1. 找到可操作当前对象的MessageConverter
    判断那个Converter 支持操作当前对象(Person对象),找到支持的Converter,把当前 Converter 支持的媒体类型统计出来(得到系统的底层能力)
  • 当前请求(@ResponseBody)的支持 Converter 为 MappingJackson2XmlHttpMessageConverter.class,MappingJackson2HttpMessageConverter
  • 将这两个 Converter 支持的媒体类型统计出来
 while(true) {
     while(var6.hasNext()) {
         HttpMessageConverter<?> converter = (HttpMessageConverter)var6.next();
         if (converter instanceof GenericHttpMessageConverter && targetType != null) {
             if (((GenericHttpMessageConverter)converter).canWrite(targetType, valueClass, (MediaType)null)) {
                 result.addAll(converter.getSupportedMediaTypes());
             }
         } else if (converter.canWrite(valueClass, (MediaType)null)) {
             result.addAll(converter.getSupportedMediaTypes());
         }
     }

     return result;
 }
  1. 激动人心的匹配环节
    浏览器支持的媒体类型SupportedMediaTypes 与 服务器产生的媒体类型 producibleType 匹配
 while(var15.hasNext()) {
     mediaType = (MediaType)var15.next();
     Iterator var17 = producibleTypes.iterator();

     while(var17.hasNext()) {
         MediaType producibleType = (MediaType)var17.next();
         if (mediaType.isCompatibleWith(producibleType)) {
             mediaTypesToUse.add(this.getMostSpecificMediaType(mediaType, producibleType));
         }
     }
 }

2. 内容协商原理总结

内容协商原理:

  1. 判断当前响应头中是否已经有确定的媒体类型
  2. 获取客户端Accept请求头字段
  3. 遍历循环所有当前系统的 MessageConverter,看谁支持操作这个对象
  4. 找到支持操作当前操作对象的converter,把converter支持的媒体类型统计出来
  5. 进行内容协商得到最佳匹配媒体类型

三、基于请求参数的内容响应

SpringBoot支持通过 url 添加请求参数,来获得不同的响应数据类型。

1. 使用方法

步骤一: 在 application.yaml 文件中添加配置,开启基于请求参数的内容协商过程:

spring:
  mvc:
    contentnegotiation:
      favor-parameter: true #开启参数方式的内容协商模式

步骤二: 发请求方式:通过 format = XXX ,标注接收的返回类型

http://localhost:8080/jsonTest?format=XML

2. 基于请求参数的内容响应原理

(1)开启内容协商机制后,内容管理器加入基于参数的内容协商策略:

在这里插入图片描述
(2) ParameterContentNegotiation 优先 —— 得到参数,直接返回该参数的媒体类型

在这里插入图片描述

四、自定义 MessageConverter

实现多协议数据兼容 —— json、xml、x-guigu

1. 回顾返回值响应过程

  1. @ResponseBody 响应数据出去 调用 RequestResponseBodyMethodProcessor 处理;
  2. Processor 处理方法返回值 —— 通过 MessageConverter 处理;
  3. 所有 MessageConverter 合起来可以支持各种媒体类型数据的操作(读、写);
  4. 内容协商找到最终的 messageConverter;

2. 需求

  1. 浏览器发的请求,返回xml —— [application/xml] —— jacksonXmlConverter
  2. ajax发请求,返回json —— [application/json] —— jacksonJsonConverter
  3. app发请求,返回自定义协议数据 —— [application/wanqing] ——wanqingConverter
    格式:属性一;属性二;…

3. 自定义 Converter 步骤

  1. 添加自定义的 MessageConverter 进入系统底层
  2. 系统底层会统计出所有的 MessageConverter 能操作哪种类型
  3. 客户端内容协商 [wanqing ------ > wanqing]

添加默认 Converter 原理 —— WebMvcConfigurationSupport.class

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 var3) {
     }

     messageConverters.add(new AllEncompassingFormHttpMessageConverter());
     if (romePresent) {
         messageConverters.add(new AtomFeedHttpMessageConverter());
         messageConverters.add(new RssChannelHttpMessageConverter());
     }

     Jackson2ObjectMapperBuilder builder;
     // 导入了jackson处理xml的包,xml的converter就会自动进来
     if (jackson2XmlPresent) {
         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) {
         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) {
         builder = Jackson2ObjectMapperBuilder.smile();
         if (this.applicationContext != null) {
             builder.applicationContext(this.applicationContext);
         }

         messageConverters.add(new MappingJackson2SmileHttpMessageConverter(builder.build()));
     }

     if (jackson2CborPresent) {
         builder = Jackson2ObjectMapperBuilder.cbor();
         if (this.applicationContext != null) {
             builder.applicationContext(this.applicationContext);
         }

         messageConverters.add(new MappingJackson2CborHttpMessageConverter(builder.build()));
     }

 }

4. 自定义Converter案例

修改SpringMVC,只有一个入口 —— 给容器中添加一个 WebMvcConfigurer

步骤一:通过extendMessageConverters向容器中添加我们自定义的Converter

package com.example.demo2.config;

import com.example.demo2.Converter.WanqingMessageConverter;
import com.example.demo2.bean.Pet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer{

    //1、WebMvcConfigurer定制化SpringMVC的功能
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {

            // 添加额外的 Converter
            @Override
            public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
                converters.add(new WanqingMessageConverter());
            }

        };
    }
}

步骤二: 自定义 WanqingMessageConverter

package com.example.demo2.Converter;

import com.example.demo2.bean.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class WanqingMessageConverter implements HttpMessageConverter<Person> {


    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return false; // 不支持读
    }

    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return aClass.isAssignableFrom(Person.class); // 是Person类型就能读写
    }

    // 统计所有MessagerConverter都能写出那种类型
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/wanting");
    }

    @Override
    public Person read(Class<? extends Person> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    // 自定义协议的写出
    @Override
    public void write(Person person, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        String data = person.getUserName() + ";" + person.getAge() + ";";
        OutputStream body = httpOutputMessage.getBody();
        body.write(data.getBytes());
    }
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值