Search code examples
spring-mvcjacksonspring-annotations

Understanding Spring mvc produces/consumes and Jackson


I am running a Spring MVC 3 maven app with embedded jetty with configuration below:

    <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.14</version>
        <configuration>
            <scanIntervalSeconds>10</scanIntervalSeconds>
            <testClassesDirectory>/Users/mydownloads/Downloads/jackson-all-1.8.10.jar</testClassesDirectory>
            <useTestClasspath>true</useTestClasspath>
        </configuration>
    </plugin> 

As seen above, I have jackson-all-1.8.10 jar in the test classpath.

I have mappings like below which are working fine when I produce json from my controller:

@RequestMapping(value="/getSomething",produces="application/json",method=RequestMethod.GET)

However, when I try to have a POST mapping so then I get an error: 415: Unsupported Media Type

the annotation I am using for POST is:

@RequestMapping(value="/postSomething", consumes="application/json", method= RequestMethod.POST)

How can I fix this so that the jackson jar sitting in the classpath takes care of the media type?

On the client when I am making a request to POST the data the request has following headers:

Request URL:http://localhost:8080/myapp/postSomething
Request Method:POST
Status Code:415 Unsupported Media Type
**Request Headersview source**
  Accept:*/*
  Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
  Accept-Encoding:gzip,deflate,sdch
  Accept-Language:en-US,en;q=0.8
  Connection:keep-alive
  Content-Length:23
  Content-Type:application/x-www-form-urlencoded
  Cookie:JSESSIONID=1f0mox1qw67zl
  Host:localhost:8080
  Origin:http://localhost:8080
  Referer:http://localhost:8080/myapp/
  X-Requested-With:XMLHttpRequest

I have datatype: 'json' on jQuery


Solution

  • You don't set the request Content-Type correctly.

    As you can see in the headers you posted, the Content-Type header value is application/x-www-form-urlencoded, which is jquery default.

    Use contentType: 'application/json' attribute in jquery ajax call.

    The dataType attribute tells jquery what content type is to be expected in the response.