我在使用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;
}
添加回答
舉報
0/150
提交
取消