视图解析器
MVC 配置简化了视图解析器的注册。
以下示例通过使用 JSP 和 Jackson 配置内容协商视图解析,将默认的 View
设置为 JSON 渲染:
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.enableContentNegotiation(new MappingJackson2JsonView());
}
}
不过,请注意,FreeMarker、Groovy Markup 和脚本模板也需要配置底层的视图技术。以下示例适用于 FreeMarker:
@Configuration
public class FreeMarkerConfiguration implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.enableContentNegotiation(new MappingJackson2JsonView());
registry.freeMarker().cache(false);
}
@Bean
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/freemarker");
return configurer;
}
}