Spring boot controller content negotiation

You can use ContentNegotiationConfigurer

Firstly, you should override the configureContentNegotiation method in your configuration class:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false).
            favorParameter(true).
            defaultContentType(MediaType.APPLICATION_JSON).
            mediaType("xml", MediaType.APPLICATION_XML);
    }
}

favorParameter(true) – enabling favoring path expressions over parameter or accept headers.

defaultContentType(MediaType.APPLICATION_JSON) – sets the default content type. this means that if you don’t pass a path expression then Spring will generate JSON as response.

mediaType("xml", MediaType.APPLICATION_XML) – sets the path expression key for XML.

Now if you declare your Controller like:

@Controller
class AccountController {

    @RequestMapping(value="/accounts", method=RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody List<Account> list(Model model, Principal principal) {
        return accountManager.getAccounts(principal) );
    }
}

and call it something like localhost:8080/app/accounts.json, then Spring will generate JSON as response. So if you call localhost:8080/app/accounts.xml you will receive XML response

You can find more info about this here.

Leave a Comment