0

I receive 415 HTTP Unsupported Media Type error with the following code:

Spring MVC Controller:

    @RequestMapping(value="/addItem", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> addItem(@RequestBody final ToDoItem item) {
        toDoItemDao.create(item);
        return new ResponseEntity<String>(HttpStatus.OK);
    }

JavaScript AJAX request:

$.ajax({
    url: ToDoDemo.serverRoot + "/addItem",
    type:'POST',
    contentType: 'application/json',
    dataType:"json",
    data: JSON.stringify(oItem),
    success: function() {
    ...
    },
    error: function(jqXHR, strStatus, strErrorThrown) {
    ...
    }
});

pom.xml:

  <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.8</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.8</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.7</version>
    </dependency>

There are plenty of similar questions on StackOverflow I tried to use solutions from them, but none of the worked for me. What am I missing?

Ivan Mushketyk
  • 8,107
  • 7
  • 50
  • 67

2 Answers2

2

Have a look at this answer for a working demo of an ajax JSON POST call to a spring MVC controller, returning a JSON response (uses Spring 3.2.1.RELEASE).

With the chrome debugger tools or Firebub, make sure that the HTTP request contains:

Content-Type: application/json

These two jackson jars are needed on the classpath, see the demo pom.xml:

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
  </dependency>

  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
  </dependency>

Make sure the @Controller is being scanned correctly, it should say if it's initialized in the logs.

Community
  • 1
  • 1
Angular University
  • 42,341
  • 15
  • 74
  • 81
0

I had to add

<mvc:annotation-driven/>`

to my Spring Context. Now everything works fine.

Ivan Mushketyk
  • 8,107
  • 7
  • 50
  • 67