在主流数据中,一般都是给客户端返回json格式数据,但可能在某些场景下,我们需要自定义返回数据格式,那么就需要添加自定义HTTP消息转化器
首先,需要写出自定义的converter
package com.chen.boot01helloworld.converter;
import com.chen.boot01helloworld.Bean.Dog;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
/**
* Created by 莫荒 on 2022/9/16 15:30
* 自定义的Converter
*/
public class MyMessageConverter implements HttpMessageConverter<Dog> {
// 是否可读
@Override
public boolean canRead(Class<?> aClass, MediaType mediaType) {
return false;
}
// 是否可写
@Override
public boolean canWrite(Class<?> aClass, MediaType mediaType) {
return aClass.isAssignableFrom(Dog.class);//如果是Dog则可写
}
// 处理哪种类型数据:application/xxx
@Override
public List<MediaType> getSupportedMediaTypes() {
return MediaType.parseMediaTypes("application/x-dog");
}
@Override
public Dog read(Class<? extends Dog> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
public void write(Dog dog, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
//自定义内容数据的写出
String data="狗的名字:"+dog.getName()+"狗的年龄"+dog.getAge();
//写出
OutputStream body = httpOutputMessage.getBody();
body.write(data.getBytes());
}
}
然后,我们将自定义的converter添加到WebMvcConfigurerd的bean中
package com.chen.boot01helloworld.config;
import com.chen.boot01helloworld.converter.MyMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* Created by 莫荒 on 2022/9/14 16:29
*/
@Configuration
public class WebConfig {
// WebMvcConfigurer定制化SpringMVC的功能的入口
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
//添加自定义HTTP消息转化器(给页面返回何种格式的数据)
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyMessageConverter());//添加自定义的convert
}
};
}
}
接下来以postman作为客户端去调用接口,并在body中指定需要返回的数据格式
在这里作者指定了Accept为:application/x-dog
调用接口:localhost:8080/dog?name=旺财&age=18
可以看到返回的数据格式是accept指定的格式,也就是我们自定义的格式:
over