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

2024-02-29

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

json 响应正在以内容类型发送回text/html当我希望他们成为application/json.

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


我确信有几种方法可以解决这个问题。这是对我有用的一个。

我通过查看发现了这一点有关自定义视图解析器的 Spring Boot 文档 https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-view-resolvers。这让我看到ThymeleafAutoConfiguration 类 https://github.com/spring-projects/spring-boot/blob/v2.1.7.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java。然后,在 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐