我用的Spring版本为4.2.5
当配置文件中加了<mvc:annotation-driven/>
后, 如果用@ResponseBody 返回JSON时, 会报406错误, 信息如下:
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
意思是生成的格式和接收的格式不相符, 于是加各种配置试, 以为是编码的问题, 结果发现没半毛钱关系...
**跟踪Spring代码, 发现Spring默认ContentNegotiationManager使用org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy解析可接受的media type**
**这是Spring3以后的新特性**
我的url-pattern设置的xxx.c , 所以能解析出来的 media type只是 text/html自然报错, 而另一个HeaderContentNegotiationStrategy根本没发挥作用
解决方法如下:
在Spring配置文件中加入如下配置:
<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/>
之后就不起作用了
文章评论