Spring MVC HTTP Status 406 - workaround

 The version of Spring used is 4.2.4, and I encountered this error when using the @ResponseBody annotation to return the json format: "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers. ". The literal meaning is obvious, the generated format does not match the acceptable format, and it does not match the eyes. But after all kinds of google and stackoverflow, most of the answers just say to add json related dependencies and so on, and it is useless to try. So I tracked the code and found that Spring's default ContentNegotiationManager uses org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy to parse acceptable media types, which seems to be a feature of Spring 3 and later, because my url-pattern is in *.htm format , so the only media type that can be parsed is text/html, and an error is naturally reported. And another HeaderContentNegotiationStrategy doesn't work at all.

  A working solution:

  Add in 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>

These two beans process the request mapping. By default, a ContentNegotiationManager using HeaderContentNegotiationStrategy will be created in the bean, so that the type in the http request header Accept can be parsed. But it should be noted that the above two beans should be defined before <mvc:annotation-driven/>. why? Because <mvc:annotation-driven/> will register RequestMappingHandlerMapping, RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver, etc., if the above two bean definitions are placed after <mvc:annotation-driven/>, it will not work.

  

  

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326682447&siteId=291194637