How to set up native MediaType in Spring MVC?

Using Spring MVC, I have controllers already working in both JSON and XML formats. In the content negotiation configuration, I would like to rely only on the Accept header and enter my own type of name carrier, 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);
}

This works very well, the Accept header: application/jsoncreates JSON, application/xmlcreates XML. Everything else returns 406 Not acceptable, even myXml.

I was expecting xml though ...

+5
source share
1 answer

With this configuration, you basically:

  • "json → application/json" "xml → application/xml" "myXml → application/xml" /params . ( )
  • Spring MVC, , HTTP "Accept: */*" Accept, ContentType "application/xml"

, .

, HttpMessageConverters (. ), , Jaxb2RootElementHttpMessageConverter ( JAXB) MappingJackson2XmlHttpMessageConverter ( Jackson) "application/xml" , "myXml".

, "myXml" "" RequestMapping - , , 406.

- "application/vnd.foobar.v.1.0 + xml", :

  • - http-.
  • xml HttpMessageConverters Spring "application/xml" "application/* + xml".

defaultContentType (, , ) .

"" .

+3

All Articles