内容协商:根据客户端接收能力不同,返回不同媒体类型的数据。
例如给定以下类返回该类的数据:
public class person {
private String name;
private String adress;
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
", adress='" + adress + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
}
pom文件中依赖jar:
```xml
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
当我们自己定义参数类型时候
定义自己的mvc配置类:
@Configuration
public class Myconfig{
@Bean
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
//自定义内容convert
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyDefineConveter());
}
};
return webMvcConfigurer;
}
}
定义自己的converter:
public class MyDefineConveter implements HttpMessageConverter<person> {
@Override
public boolean canRead(Class clazz, MediaType mediaType) {
return false;
}
@Override
public boolean canWrite(Class clazz, MediaType mediaType) {
return clazz.isAssignableFrom(person.class);
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return MediaType.parseMediaTypes("application/x-mydefine");
}
@Override
public person read(Class<? extends person> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
//自定义的类型数据
public void write(person person, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
String data = person.getName()+","+person.getAdress();
OutputStream body = outputMessage.getBody();
body.write(data.getBytes(StandardCharsets.UTF_8));
}
}
然后在yaml文件配置:
spring:
mvc:
# 内容协商
contentnegotiation:
favor-parameter: true
media-types: #媒体类型
json: application/json #json类型
xml: application/xml #xml类型
gg: application/x-mydefine #自定义类型
给请求地址配上&format=json或&format=xml
例如
http://localhost:8080/test/person?format=xml
返回的数据是xml类型
&format=json返回的是json数据
浏览器地址栏:http://localhost:8080/test/person?format=gg 就可以得到自定义的数据