The resource identified by this request is only capable of generating responses with characteristics
【转】今天在调试springMVC的时候,在将一个对象返回为json串的时候,浏览器中出现异常:
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().
从网上查了下,说是让配置下json转化bean:
运行下面代码
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean>
配置完运行后还是报上述错误。
应该不是配置原因,从http://forum.spring.io/forum/spring-projects/web/82137-spring-3-and-ajax这个网址中查出以下配置:
运行下面代码
<bean id="messageAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- Support JSON --> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean> <bean id="exceptionMessageAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver"> <property name="messageConverters"> <list> <!-- Support JSON --> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/> </list> </property> </bean>
其中第一个和之前的配置没有什么差别,但是第二个exceptionMessageAdapter,这个是处理转化json异常的适配器(这个配置对于调试查找问题还是非常有用的)。
当用这个配置替换上面的配置时,浏览器报了如下异常:
org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
经查,在http://blog.csdn.net/xplizm/article/details/8205882这篇博文中,提到出现这个问题的原因是因为,@ResponseBody返回的对象中的属性缺少set\get方法。
将返回对象加上set\get方法后,一切ok。
这是xplizm的博文中的总结:
开始总以为是Content-Type或者Accept属性有问题,但找了半天原因才发现这里有个基本的要求:POJO对象要转成Json,则要求POJO中的属性必须都有getter方法,加上getter方法后就正常了 :)
ps:
1.当最后调试正确后,我把上述的配置都注释掉,并加上下面这两个配置:
<context:annotation-config />
<mvc:annotation-driven />
发现也可以正常使用。这说明,可以使用上面的两个简单说明就可以使用springMVC的@ResponseBody注解,并返回json串。
2. 调试配置也是很重要的,调试时报出的异常要比tomcat直接返回的406码要直接的多,更近的接近真相;
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().这个问题加了上面两个配置以后终于解决了,可喜可贺。
转载自csdn:打开 ;
本文作者:方方和圆圆
本文链接:https://www.cnblogs.com/diligenceday/p/4715045.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?