一、内容协商的含义:通过请求路径中加参数来决定要返回的数据格式为json还是xml.
二、操作步骤:
0.

        <dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>

1.在配置文件中进行配置:

spring.mvc.contentnegotiation.favor-parameter=true

2.定义一个实体类和返回实体类实例的控制器类:

package com.example;

public class Student {
private int id;
private String name;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
package com.example.controller;

import com.example.Student;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PathController {

@GetMapping(value="/projects/spring-boot")
public Student getStudent(){
Student s=new Student();
s.setId(1);
s.setName("Newton");

return s;
}
}

3.通过postman请求接口,分别带format参数,

SpringBoot 官方文档示例:(52)内容协商_java

SpringBoot 官方文档示例:(52)内容协商_spring boot_02

可以看到,format为json时,会返回json字符串,format为xml时,会返回xml字符串.
可以通过如下配置修改这个默认的format参数:

spring.mvc.contentnegotiation.parameter-name=myparam

这样配置之后请求路径就要改为:
​​​ http://localhost:8073/projects/spring-boot?myparam=xml​​​ 或
http://localhost:8073/projects/spring-boot?myparam=xml


后缀匹配:
配置:

spring.mvc.contentnegotiation.favor-path-extension=true
spring.mvc.pathmatch.use-suffix-pattern=true

加了这2个配置之后,/projects/spring-boot.json 这个请求可以匹配/projects/spring-boot这个请求路路径