Spring content negotiating view resolver

Jan 1, 0001

Returning HTML or JSON data from the same controller is a valuable thing to have. Code once, use for HTML interfaces or API interfaces. How does it work? Like this:

curl http://localhost/data.json

retruns

{
 data:[1,2,3]
}

and a request to the same url without the extionsion curl http://localhost/data returns

<html>
..
data 1,2,3
</html>

and the code for the controller is the same, maybe something like

public String controller(Map<String,Object> model) {
 model.put("data", Arrays.asList(1,2,3));
 return "viewname";
}

Spring will automatically detect the extension and return the correct view. Here is the configuration:

@Configuration
public class WebConfigurationAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(true)
                .defaultContentType(MediaType.TEXT_HTML)
                .ignoreAcceptHeader(true)
                .mediaType("html", MediaType.TEXT_HTML)
                .mediaType("json", MediaType.APPLICATION_JSON);
        super.configureContentNegotiation(configurer);
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        jsonView.setPrettyPrint(true);
        registry.freeMarker();
        registry.enableContentNegotiation(jsonView);
        super.configureViewResolvers(registry);
    }
}