【轉】今天在調試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:打開 ;
文章列表