SpringMVC uses @ResponseBody annotation to convert json to several situations where 406 appears

Today, there was a 406 error when returning json data with SpringMVC test. I checked many articles on the Internet and did not solve it. Let me list the most common situations:

1. The Jackson package is not imported correctly.

My dependency is already added

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.10.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.10.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.10.0</version>
</dependency>

There are also corresponding libraries
Insert picture description here

Two, SpringMVC version and Jackson version are not compatible

The SpringMVC version I use is 4.1.2-RELEASE, and the Jackson version is 2.10.0 above. There is no problem in this place.

Three, there is no configuration to load the corresponding HttpMessageConverter

Spring defaults to six HttpMessageConverters. To achieve json conversion, you need to load Jackson's HttpMessageConverter. If it is configured separately, add it in the springmvc configuration file

<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>
Or add annotation-driven tags, generally this method
<mvc:annotation-driven/>

Fourth, the url-pattern of DispatcherServlet ends with .html

My web.xml configuration is

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

There is no such problem with the end of .html. If there is such a problem, you can change it. If you must use the end of .html, add another url-pattern

<servlet-mapping>
        <servlet-name>dispatch</servlet-name>
        <url-pattern>*.html</url-pattern>
        <url-pattern>*.json</url-pattern>
 </servlet-mapping>

Five, there is a problem with the class used for conversion

This is my situation. When I wrote an interface temporarily for the learning front end, I simply defined a class without a get method, so the 406 situation appeared. So just add the get method to the properties of the class.

Guess you like

Origin blog.csdn.net/Baibair/article/details/104859190