混合html和json模板时如何在thymeleaf中正确设置内容类型

时间:2019-07-17 10:07:48

标签: spring thymeleaf

我正在使用Spring Boot和thymeleaf开发单页应用程序。我有两种模板;一个将SPA脚手架页面生成为html,并多个生成json响应。

当我希望它们为text/html时,将以内容类型application/json发送回json响应。

如何正确设置内容类型?我需要两个百里香视图解析器吗?我在@Controller上尝试了@GetMapping(value = Routes.EVENTS, produces = MediaType.APPLICATION_JSON_VALUE),但没有任何效果。

1 个答案:

答案 0 :(得分:1)

我敢肯定有几种方法可以解决这个问题。这是为我工作的人。

我通过查看Spring Boot documentation on custom view resolvers来弄清楚。这使我着眼于ThymeleafAutoConfiguration class。然后在Spring框架中进行一些明智的调试有助于弥补这一空白。

@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;
}