我通过更改配置文件和分配订单来查看解析器来使其工作。据我了解,看起来它首先尝试使用ContentNegotiation解析视图,如果失败,则退回到Thymeleaf解析器。我将其标记为答案,如果有人有更好的方法或建议的更正,请告诉我。
package com.gojha.web;import java.util.ArrayList;import java.util.List;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.http.MediaType;import org.springframework.web.accept.ContentNegotiationManager;import org.springframework.web.servlet.View;import org.springframework.web.servlet.ViewResolver;import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;import org.springframework.web.servlet.view.json.MappingJackson2JsonView;import org.thymeleaf.spring4.SpringTemplateEngine;import org.thymeleaf.spring4.view.ThymeleafViewResolver;import org.thymeleaf.templateresolver.ServletContextTemplateResolver;import org.thymeleaf.templateresolver.TemplateResolver;@Configuration@EnableWebMvc@ComponentScan("com.gojha.web")public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } @Bean public ViewResolver viewResolver() { TemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine); viewResolver.setOrder(2); return viewResolver; } @Bean public ViewResolver cnViewResolver(ContentNegotiationManager cnm) { ContentNegotiatingViewResolver cnvr = new ContentNegotiatingViewResolver(); cnvr.setContentNegotiationManager(cnm); cnvr.setOrder(1); List<View> views = new ArrayList<View>(); views.add(jsonView()); cnvr.setDefaultViews(views); return cnvr; } @Bean public View jsonView() { MappingJackson2JsonView view = new MappingJackson2JsonView(); view.setPrettyPrint(true); return view; }}


