一、介绍
(1)找到对应的返回值处理器,如方法标注了@ResponseBody,则使用ResponseBody返回值处理器。
(2)ResponseBody返回值处理器先判断是否是流式数据,再进行内容协商。
(3)内容协商先找到对应的内容协商管理器,如参数内容协商策略、请求头内容协商策略,利用上述内容协商策略获取浏览器支持的内容类型。
(4)找到能处理该返回值的消息转换器并记录其支持的内容类型,然后根据内容类型权重找到消息转换器处理返回值。
二、参数内容协商策略
(1)开启默认的参数内容协商策略
spring.mvc.contentnegotiation.favor-parameter=true
(2)自定义内容协商策略
@Configuration(proxyBeanMethods = false)
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
Map<String, MediaType> mp = new HashMap();
mp.put("wsh", MediaType.parseMediaType("application/json"));
ParameterContentNegotiationStrategy pcs = new ParameterContentNegotiationStrategy(mp);
configurer.strategies(Arrays.asList(pcs));
}
}
三、自定义消息转换器(可用在@ResponseBody和@RequestBody)
(1)编写配置类
@Configuration(proxyBeanMethods = false)
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new HttpMessageConverter<Person>() {
@Override
public boolean canRead(Class<?> aClass, MediaType mediaType) {
return false;
}
@Override
public boolean canWrite(Class<?> aClass, MediaType mediaType) {
return aClass.isAssignableFrom(Person.class);
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return MediaType.parseMediaTypes("application/wsh");
}
@Override
public Person read(Class<? extends Person> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
public void write(Person person, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
OutputStream body = httpOutputMessage.getBody();
body.write((person.getName() + " " + person.getAge()).getBytes());
body.flush();
}
});
}
}
(2)编写Controller
@Controller
public class HelloController {
@GetMapping("/user")
@ResponseBody
public Person getUser(){
Person person = new Person("wsh", 20);
return person;
}
}