1、json
1.1 引入Springboot web包,帮我们自动导入json处理
<!-- 启动器-web-Mvc环境依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1.2 方法上加@ResponseBody注解
@ResponseBody
@GetMapping("/json")
public User getUser(){
User user = new User();
user.setName("yan");
user.setDepartId(1L);
user.setPassword("123456");
return user;
}
测试:
http://localhost:8003/yan/json
{"id":null,"name":"yan","password":"123456","sex":null,"age":null,"createTime":null,"updateTime":null,"deleted":null,"version":null,"departId":1}
2、内容协商
根据客户端接收数据不同,返回不同的类型数据。
2.1 引入xml包
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
2.2 请求头的Accept字段告诉服务器可以处理类型字段
2.3 开启浏览器参数内容协商功能
浏览器写请求头自定义为json或xml
在application.yml文件中
spring:
mvc:
contentnegotiation:
favor-parameter: true(默认为false)
http://localhost:8003/yan/json?format=json
{"id":null,"name":"yan","password":"123456","sex":null,"age":null,"createTime":null,"updateTime":null,"deleted":null,"version":null,"departId":1}
2.4 原理
1、判断当前响应头中是否已经有确定的媒体类型,MediaType
2、获取客户端(postman、浏览器)支持的内容类型(获取客户端Accept请求头字段) [application/xml]
3、contentNegotiationManager内容协商管理器,默认使用基于请求头的策略,默认只有一个策略
-
调用HeaderContentNegotiationStrategy来确定客户端可以接收的内容类型
-
遍历循环所有当前系统的MessageConverter,看谁支持操作这个对象
-
找到支持操作的Converter,把converter支持的媒体类型统计出来
-
客户端需要[application/xml],服务端能力[10种\json\xml]
-
进行内容协商的最佳匹配
-
用支持 将对象转为最佳匹配媒体类型的converter,调用它进行转换
后四个支持把对象转为json/xml