栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot修改内容协商管理器(自定义消息类型转换器)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot修改内容协商管理器(自定义消息类型转换器)

基于请求参数的内容协商策略只支持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 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());
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/845287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号