xmljsonspringspring-mvccontent-negotiation

How to configure custom MediaType in Spring MVC?


Using Spring MVC, I have controllers already working for both JSON and XML media formats. In the content negotiation configuration, I would like to rely on Accept header only, and introduce a custom name media type, for example: "myXml"

My configuration:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer
           .favorPathExtension(false)
           .favorParameter(false)
           .ignoreAcceptHeader(false)
           .useJaf(false)
           .mediaType(MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON)
           .mediaType(MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_XML)
           .mediaType("myXml", MediaType.APPLICATION_XML)
           .defaultContentType(MediaType.APPLICATION_JSON);
    }
}

My Controller:

@RequestMapping(value = "/manager/{id}",
        method = RequestMethod.GET,
        produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}
)
@ResponseBody public Manager managers(@PathVariable long id){
    return repo.getManagerById(id);
}

It works pretty well, Accept header: application/json produces JSON, application/xml produces XML. Anything else returns 406 Not Acceptable, even myXml.

I expected xml though...


Solution

  • With that configuration, you basically:

    I don't think you intended to handle content negotiation like this.

    You probably want to customize HttpMessageConverters (see here), like registering a Jaxb2RootElementHttpMessageConverter (if using JAXB) or a MappingJackson2XmlHttpMessageConverter (if using Jackson) and registering them with both "application/xml" and "myXml" media types.

    Also, don't forget to add "myXml" in the "produces" part of the RequestMapping annotation - your controller method should declare it as a media type it can produce, otherwise it will will throw 406 again.

    My advice

    You should definitely use a media type like "application/vnd.foobar.v.1.0+xml" since:

    In that case you can juste keep the defaultContentType part in your configuration (and probably set it to your custom media type) and throw away the rest.

    In any case, you should still declare this custom media type in the produces section of your mapping annotations.