基于请求参数的内容协商策略只支持jaon,和xml两种形式的。【使用消息转换器的请求参数的形式进行内容协商的话他的请求头拥有固定的参数名称】
在内容协商管理器中想要基于请求头的内容协商和基于请求路径的内容协商都起作用:
在配置类中的配置:
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
//自定义内容协商的策略,这个不是增加是进行全面的替换
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
//使用这个参数的类型的原因就是:public ParameterContentNegotiationStrategy(@Nullable java.util.Map mediaTypes)
HashMap stringMediaTypeHashMap = new HashMap<>();
stringMediaTypeHashMap.put("json",MediaType.APPLICATION_JSON);
stringMediaTypeHashMap.put("xml",MediaType.APPLICATION_ATOM_XML);
stringMediaTypeHashMap.put("gg",MediaType.parseMediaType("application/x-guigu"));
//指定解析参数哪些参数对应白那些媒体类型
ParameterContentNegotiationStrategy parameterContentNegotiationStrategy = new ParameterContentNegotiationStrategy(stringMediaTypeHashMap);
//是用来设置在请求头的方式中也适用的参数。
HeaderContentNegotiationStrategy headerContentNegotiationStrategy = new HeaderContentNegotiationStrategy();
configurer.strategies(Arrays.asList(parameterContentNegotiationStrategy,headerContentNegotiationStrategy));
}
//是用来为springMVC的底层添加一个新的消息转换器
@Override
public void extendMessageConverters(List> converters) {
converters.add(new GuiguMessageConverter());
}
};
}
自定义消息类型转换器:代码
消息转换器需要实现的接口:
** * 自定义的Converter * * * HttpMessageConverter是全部消息转换器的顶级接口 */ public class GuiguMessageConverter implements HttpMessageConverter { // 配置这个消息转换器是不是可以读 @Override public boolean canRead(Class> clazz, MediaType mediaType) { return false; } // 配置这个消息转换器是不是可以写 如果返回的是Peron类型的数据就支持 @Override public boolean canWrite(Class> clazz, MediaType mediaType) { return clazz.isAssignableFrom(Person.class); } @Override public List getSupportedMediaTypes() { return MediaType.parseMediaTypes("application/x-guigu"); } @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.getUserName()+";"+person.getAge(); //写出去 使用流的方式进行 OutputStream body = outputMessage.getBody(); body.write(data.getBytes()); } }



