您的位置:首页 > 编程语言 > Java开发

Spring MVC HTTP Status 406 - 解决方法

2016-05-17 23:30 375 查看

 用的Spring版本是4.2.4,在用@ResponseBody标注返回json格式时候遇到这样的错误:“The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.”。字面意思很明显,产生的格式跟能接受的格式不符,对不上眼。但是各种google、stackoverflow之后,大多数答案都只是说要加上json的相关依赖之类的,试了都无用。于是跟踪代码,发现Spring默认ContentNegotiationManager使用org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy解析可接受的media type,这貌似是Spring 3哪个版本以后开始的特性,因为我的的url-pattern 是*.htm格式的,于是解析出来能accept的media type只有text/html,自然报错。而另一个HeaderContentNegotiationStrategy根本没发挥作用。

  一个可行的解决方案:

  在spring-servelt中添加

<bean   class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

        <property name="messageConverters">

            <list>

                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

            </list>

        </property>

    </bean>

这两个bean处理请求映射的,在bean中默认会创建一个使用HeaderContentNegotiationStrategy的ContentNegotiationManager,这样就能解析htttp请求头Accept中的类型了。但要注意的是,上述两个bean要定义在<mvc:annotation-driven/>之前。为什么呢?因为<mvc:annotation-driven/>会注册RequestMappingHandlerMapping, RequestMappingHandlerAdapter以及 ExceptionHandlerExceptionResolver等等的东西,如果上述两个bean定义放在<mvc:annotation-driven/>之后就不起作用了。

  

  

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐