EDIT - This is now solved, the error was in my spring configuration. I had missed the <mvc:annotation-driven/> tag. When adding it, everything worked as expected.
I recently asked this question at stackoverflow but it didn't get that much attention so I am trying here as well.
I have defined a controller using Spring MVC that should accept HTTP GET requests to the address /controllertest only if the content type of the request is application/json. It also returns data in application/json and therefore only requests that accept data in that format should pass. However, this does not work.
This is my code using Spring 3.2.0:
Code:
package test.controllers;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/controllertest")
public class TestController {
@RequestMapping(method = GET, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String helloJSON() {
return "{\"message\":\"HelloWorld\"}";
}
}
This is what I excpect:
- If I use any HTTP method other than GET I should receive a 405 - Method not allowed response
- If I send a request that do not accept application/json I should receive a 406 Not Acceptable response.
- If I send a request with a Content-Type other than application/json I should receive a 415 Unsupported Media Type response.
This is the actual result:
- When sending HTTP POST I do actually get a 405 - Method not allowed. Very nice.
- When sending a request with an Accept header with text/xml only I get a 200 - OK response and the content type of the response is text/xml even though the method only produces application/json.
- When sending a request where the content type is text/xml I get a 200 - OK response.