The resource identified by this request is only capable of generating responses with characteristics

问题描述:

使用@ResponseBody返回实体异常:
HTTP Status 406 :The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers

原因分析:

AbstractMessageConverterMethodProcessor.writeWithMessageConverters()
实际上此时调用的是子类RequestResponseBodyMethodProcessor

在这里插入图片描述
在这里插入图片描述

重点在 contentNegotiationManager ; contentNegotiationManager 由构造器产生, 构造器可以允许传null, 如果传入null将默认创建一个ContentNegotiationManager对象
在这里插入图片描述在这里插入图片描述
那么, 问题就是谁创建了这个对象, 并且contentNegotiationManager这个集合字段是在哪里创建的:
答案是:RequestMappingHandlerAdapter
在这里插入图片描述
在这里插入图片描述
而在RequestMappingHandlerAdapter中 既有默认的实例化, 又有set方法可供注入
在这里插入图片描述
在这里插入图片描述

既然是afterPropertiesSet()方法, 那就是在RequestMappingHandlerAdapter实例化的时候创建的;那么RequestMappingHandlerAdapter是在哪里调用实例化的呢?
答案是:如果没有在项目中mvc的配置文件中指定的话将按默认的配置实例化,在WebMvcConfigurationSupport中
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
ServletPathExtensionContentNegotiationStrategy会根据url后缀映射对应的mediaType
在这里插入图片描述

那么解决办法就是自己创建不使用默认的;代码【解决方案】:


解决方案:

mvc的配置中增加这段:
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/plain;charset=UTF-8</value>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值