Spring 的 View 和 ViewResolver 都有很多实现类,支持如Json、XML、模版(Freemaker、Velocity)甚至Excel、PDF等形式的输出。
相关类在org.springframework.web.servlet.view包中。
其中有一个实现类:ContentNegotiatingViewResolver 可以根据对资源的描述来返回不同形式的视图
首先需要配置 ContentNegotiationManagerFactoryBean
在有@Confiuration注解的类中编写:
@Bean
public ContentNegotiationManagerFactoryBean contentNegotiationManagerFactoryBean(){
ContentNegotiationManagerFactoryBean bean=new ContentNegotiationManagerFactoryBean();
bean.setIgnoreAcceptHeader(true);
bean.setFavorPathExtension(false);
bean.setFavorParameter(true);
bean.setParameterName("format");
bean.setDefaultContentType(MediaType.TEXT_HTML);
Map<String,MediaType> map=new HashMap<>();
map.put("html",MediaType.TEXT_HTML);
map.put("json",MediaType.APPLICATION_JSON);