1.什么内容协商
简单说就是服务提供方根据客户端所支持的格式来返回对应的报文,在 Spring 中,REST API 基本上都是以 json 格式进行返回,而如果需要一个接口即支持 json,又支持其他格式,开发和维护多套代码显然是不合理的,而 Spring 又恰好提供了该功能,那便是ContentNegotiation
在 Spring 中,决定一个数据是以 jso还是xml 分别如下:
- favorPathExtension 后缀模式,例如:xxx.json,xxx.xml
- favorParameter format模式,例如:xxx?format=json,xxx?format=xml,
- 通过请求的 Accept 来决定返回的值
2.代码工程
实验目标:根据请求参数不一样自动切换不同的格式的返回结果
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ContentNegotiation</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
</dependencies>
</project>
controller
package com.et.contentnegotiation.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
@ResponseBody
public Map<String, Object> showHelloWorld(){
Map<String, Object> map = new HashMap<>();
map.put("msg", "HelloWorld");
return map;
}
}
DemoApplication.java
package com.et.contentnegotiation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
application.yaml
server:
port: 8088
spring:
mvc:
contentnegotiation:
#favor-path-extension: true # header accept
favor-parameter: true # url ?format=xml or format=json
media-types:
json: application/json
3.测试
favorParameter 方式
设置配置文件里面参数
spring.mvc.contentnegotiation.favor-parameter=true
启动springboot应用,
http://127.0.0.1:8088/hello?format=xml
http://127.0.0.1:8088/hello?format=json
返回不同格式的结果
请求的 Accept 来决定返回的值
设置配置文件里面参数
spring.mvc.contentnegotiation.favor-path-extension=true
设置header里面Accept:application/xml 或者application/json
4.引用