1

I want to serve different content types based on the Accept header I receive at a RESTful endpoint.

application/myapp-v1.0+json
application/myapp-v1.0+xml

Is there any way to do this with @ResponseBody? It seems like a convenient shortcut by allowing me to just return an object and let the HttpMessageConverter handle invoking Jackson but I just cannot get it working. 406 responses any time I wire up more than one MimeType.

For this iteration I've ended up querying the request header myself and returning the appropriate view handler myself, but I wouldn't mind revisiting this in future.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
CraigJPerry
  • 973
  • 1
  • 8
  • 16

2 Answers2

0

If you are working with Spring 3.1, you can do this using @RequestMapping. New to 3.1 for the RequestMapping annotation are these members:

  1. consumes() -- Allows you to filter by the Content-type request header.
  2. produces() -- Allows you to filter by the Accept request header.

There is also the ability to apply some simple expressions to make it more robust.

@RequestMapping(consumes = {"application/json", "application/xml"})

@RequestMapping(consumes = {"!text/plain"})
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
0

You can probably do something along the lines of what is suggested in this SO question:

Managing custom Acccept header in Spring MVC

class MyAppV1JsonConverter extends MappingJacksonHttpMessageConverter{
    public MyAppV1JsonConverter (){
        super(MediaType.valueOf("application/myapp-v1.0+json"));
        // OR setSupportedMediaTypes(Collections.singletonList(MediaType.valueOf("application‌​/myapp-v1.0+json")));
    }
}

..

Community
  • 1
  • 1
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125