JSF & Java Blog

Discussion on Java and JSF, including Spring, Maven, Eclipse and Jenkins

Spring MVC 406 status code from AJAX requests

0

Recently after upgrading from Spring MVC 3.1.2.RELEASE to 3.2.0.RELEASE, all of our AJAX requests stopped working, and instead returned a 406 status code (see here for status code meanings). We were using Jackson 2.1.2, the following snippet from the pom.xml file shows the two dependencies:

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

There were some changes made with the 3.2.0.RELEASE in regards to content negotiation. Spring now by default determines the media type by first checking the file extension. It turns out that this was causing the 406 status code, and we needed to stop Spring doing this, and instead check for the ‘Accept’ header first. This can be done by the following code in the Spring MVC configuration file:

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <!-- Turn off working out content type based on URL file extension, should fall back to looking at the Accept headers -->
    <property name="favorPathExtension" value="false" />
</bean>

This simply defines a new bean of the class ContentNegotiationManagerFactoryBean and the property favorPathExtension is set to false. We then add the content-negotiation-manager attribute to the mvc:annotation-driven element and set this new bean as the content-negotiation-manager. With this new bean defined, our AJAX requests started working again with a 200 response code.

So, what do you think ?

  • *