In Spring MVC, how can I set the mime type header when using @ResponseBody

Sean Patrick Floyd picture Sean Patrick Floyd · Dec 17, 2010 · Viewed 108.1k times · Source

I have a Spring MVC Controller that returns a JSON String and I would like to set the mimetype to application/json. How can I do that?

@RequestMapping(method=RequestMethod.GET, value="foo/bar")
@ResponseBody
public String fooBar(){
    return myService.getJson();
}

The business objects are already available as JSON strings, so using MappingJacksonJsonView is not the solution for me. @ResponseBody is perfect, but how can I set the mimetype?

Answer

Javier Ferrero picture Javier Ferrero · Dec 19, 2010

Use ResponseEntity instead of ResponseBody. This way you have access to the response headers and you can set the appropiate content type. According to the Spring docs:

The HttpEntity is similar to @RequestBody and @ResponseBody. Besides getting access to the request and response body, HttpEntity (and the response-specific subclass ResponseEntity) also allows access to the request and response headers

The code will look like:

@RequestMapping(method=RequestMethod.GET, value="/fooBar")
public ResponseEntity<String> fooBar2() {
    String json = "jsonResponse";
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}