Kevin's Zone

  • Home
  • Project
  • ContactMe
  • Login
  • Register
Kevin
受苦即了苦, 享福即消福, 福尽而死
  1. 首页
  2. 学习笔记
  3. Spring
  4. 正文

Spring4.X版本mvc:annotation-driven报406错误处理

2016年12月8日 3307点热度 0人点赞 0条评论

我用的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/>之后就不起作用了

 

 

欢迎加入技术交流群: 84436262

标签: Spring 错误处理
最后更新:2016年12月17日

Kevin

这个人很懒,什么都没留下

点赞
下一篇 >

文章评论

您需要 登录 之后才可以评论
文章目录
  • 解决方法如下:

COPYRIGHT © 2021 Kevin's Zone. ALL RIGHTS RESERVED.

京ICP备16064400号-1