"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why am I getting a 406 (Not Acceptable) Error When Sending a JSON Request to My Spring MVC Controller?

Why am I getting a 406 (Not Acceptable) Error When Sending a JSON Request to My Spring MVC Controller?

Published on 2024-11-07
Browse:528

Why am I getting a 406 (Not Acceptable) Error When Sending a JSON Request to My Spring MVC Controller?

Spring JSON Request Returning 406 (Not Acceptable)

When attempting to send a JSON request to a Spring MVC controller, some users encounter a "406 Not Acceptable" error. This issue stems from a mismatch between the requested content type ("application/json") and the response capability of the controller.

In Spring MVC, the controller method is annotated with "@ResponseBody" to indicate that the return value should be written to the HTTP response body as JSON. However, if the proper HTTPMessageConverter is not registered in the application context, Spring will be unable to convert the return value to the requested format.

A common cause of this error is the absence of the Jackson libraries in the application classpath. The Jackson libraries provide the HTTPMessageConverter responsible for converting Java objects to JSON and vice versa.

To resolve the issue, follow these steps:

  1. Ensure that the following Jackson libraries are included in the application classpath:

    • jackson-core-asl.jar
    • jackson-mapper-asl.jar
  2. If you are using Spring 3.0 or later, add the following line to the spring-servlet.xml configuration file to enable annotation-driven MVC configuration:

  3. Remove the unnecessary "headers=\"Accept=/\"" directive from the controller method annotation. This directive forces Spring to accept any header and can lead to compatibility issues.

By implementing these steps, the HTTPMessageConverter will be registered, and Spring will be able to convert the controller's return value to JSON as expected.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3