SpringBoot-内容协商

SpringBoot-内容协商

1.基本介绍

  1. 根据客户端接收能力不同,SpringBoot 返回不同媒体类型的数据

  2. 比如: 客户端 Http 请求 Accept: application/xml 则返回 xml 数据,客户端 Http 请求 Accept: application/json 则返回 json 数据

  3. 比如下面的示意图

image-20220806184033647

image-20220806184049738

2.内容协商-应用实例

● 需求说明 : 使用Postman发送Http请求,根据请求头不同,返回对应的json数据 或者 xml 数据, 如图

image-20220806184147707

image-20220806184157457

  1. 在 pom.xml 增加处理 xml 的依赖
<!-- 引入支持返回 xml 数据格式 -->
<dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
   <artifactId>jackson-dataformat-xml</artifactId>
</dependency>
  1. 使用Postman发出不同的Http Header , 可以看到返回对应的数据格式

image-20220806184256780

image-20220806184303122

  1. 切换 Postman 不同的 Accept 类型, 来 Debug 源码, 看看对应的 JsonGenerator 类型

image-20220806184321344

image-20220806185049826

注意要处理xml格式需要加入如下依赖

<!-- 引入支持返回 xml 数据格式 -->
<dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
   <artifactId>jackson-dataformat-xml</artifactId>
</dependency>
  1. 使用浏览器请求,为什么会返回 xml 数据分析,而不是 json?

image-20220806184359272

3.注意事项和使用细节

  1. Postman 可以通过修改 Accept 的值,来返回不同的数据格式

  2. 对于浏览器,我们无法修改其 Accept 的值,怎么办? 解决方案: 开启支持基于请求参数 的内容协商功能

(1)修改 application.yml, 开启基于请求参数的内容协商功能

spring:
  mvc:
#    static-path-pattern: /llp/**
    #开启页面表单的 Rest 功能
    hiddenmethod:
      filter:
        enabled: true
    #配置视图解析器
    view:
      suffix: .html
      prefix: /
    contentnegotiation:
      #开启基于请求参数的内容协商功能
      favor-parameter: true
      #指定一个内容协商的参数名
      parameter-name: llpformat
  web:
    resources:
      #修改/指定 静态资源的访问路径/位置
      #
      static-locations: ["classpath:/llpimg/","classpath:/META-INF/resources/",
                         "classpath:/resources/", "classpath:/static/", "classpath:/public/"]      #String[] staticLocations

image-20220806184816856

(2)完成测试

image-20220806184509961

(3)注意,参数 format 是规定好的 , 在开启请求参数的内容协商功能后,SpringBoot 底层 ParameterContentNegotiationStrategy 会通过 format 来接收参数,然后返回对应的媒体类型/ 数据格式 , 当然 format=xx 这个 xx 媒体类型/数据格式 是 SpringBoot 可以处理的才行,不能乱写

image-20220806184623597

image-20220806184630699

猜你喜欢

转载自blog.csdn.net/qq_44981526/article/details/126199509