为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Boot内容协商配置

Spring Boot内容协商配置

沧海一幻觉 2021-05-11 13:30:55
我在使用spring-boot配置内容协商时遇到困难。我想保留大多数默认的spring-boot配置。我遵循了以下 https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc/, 而不是最近的教程。目前,当我发送application/json或txt/html的请求时,视图似乎没有解决,但是当我打开视图时,@EnableWebMvc它似乎得到了解决。以下是我当前的配置。@Configuration // according to the spring-boot docs this should be enough with spring-boot//@EnableWebMvc  If I enable this content-negotiation seems to work without any configuration, but I loose the default spring-boot configurationpublic class MvcConfiguration implements WebMvcConfigurer {    @Bean(name = "jsonViewResolver")    public ViewResolver getJsonViewResolver() {        return new JsonViewResolver();    }    @Override    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {    // Simple strategy: only path extension is taken into account        configurer.favorPathExtension(true)            .defaultContentType(MediaType.TEXT_HTML)            .mediaType("html", MediaType.TEXT_HTML)            .mediaType("json", MediaType.APPLICATION_JSON);}    @Bean    public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {        ContentNegotiatingViewResolver resolver = newContentNegotiatingViewResolver();        resolver.setContentNegotiationManager(manager);        return resolver;    }}
查看完整描述

1 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

您没有在内容协商管理器中注册解析器。


请尝试以下修改:


@Bean

public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager){

  ContentNegotiatingViewResolver resolver = newContentNegotiatingViewResolver();

  resolver.setContentNegotiationManager(manager);

  List<ViewResolver> resolvers = new ArrayList<>();

  ViewResolver aViewResolver = getJsonViewResolver();

  resolvers.add(aViewResolver);

  resolver.setViewResolvers(resolvers);

  return resolver;

}


查看完整回答
反对 回复 2021-05-26
  • 1 回答
  • 0 关注
  • 188 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信