Search code examples
springthymeleaf

How to set content-type correctly in thymeleaf when mixing html and json templates


I'm working on a single page application using spring boot and thymeleaf. I have two kinds of templates; one producing the SPA scaffolding page as html and multiple producing json responses.

The json responses are being sent back with a content-type of text/html when I would like them to be application/json.

How do I have the content-types set correctly? Do I need two thymeleaf view resolvers? I tried @GetMapping(value = Routes.EVENTS, produces = MediaType.APPLICATION_JSON_VALUE) on the @Controller but to no effect.


Solution

  • I'm sure there are a few approaches to solving this. Here is the one that worked for me.

    I figured it out by looking in the Spring Boot documentation on custom view resolvers. This lead me to looking at the ThymeleafAutoConfiguration class. Then a bit of judicious debugging in the Spring framework helped to fill in the gaps.

    @Bean
    public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine){
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setContentType("application/json");
        viewResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        viewResolver.setOrder(1);
        viewResolver.setViewNames(new String[] {"*.json"});
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }