Video in progress
How does content negotiation work in Spring MVC, and when do the 406 and 415 errors occur?
Spring reads the request body with a suitable HttpMessageConverter based on Content-Type; if no converter fits, 415. It writes the response based on the Accept header and the method's produces value; if no agreed type is found, 406.
📖 Answer
Keep the two directions separate:
| Direction | Which header | Error |
|---|---|---|
Reading the request body (@RequestBody) |
Content-Type |
415 Unsupported Media Type |
| Writing the response | Accept + produces |
406 Not Acceptable |
RequestMappingHandlerAdapter asks the converters in its list in order: canRead(MyDto.class, application/json)? If Jackson is present, MappingJackson2HttpMessageConverter says "yes".
Cases seen in practice:
- The frontend sends
text/plain. If it sends a body withfetchand doesn't setContent-Type, the server returns 415. Don't change the controller: have the client set the header correctly. produces = "application/json", but the client sendsAccept: application/xml: 406. It usually shows up with old clients.- An error response becomes a 406. An
@ExceptionHandlerreturns aProblemDetail, but the client asked only forAccept: image/png(an image endpoint). Spring can't write the error body: the client sees an empty 406 and the original error is lost. - A Jackson class without getters. If the response object's fields are private and there's no getter, you get "No converter found for return value", a 500. Using a record fixes this.
Diagnostics:
logging:
level:
org.springframework.web.servlet.mvc.method.annotation: DEBUG
Lines like "Using 'application/json', given [/]..." in the log show which type was chosen. Checking the request headers with curl -v is the fastest way to find a 415/406.
Sign up to mark studied questions and save your progress.