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...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…