我想通过使用JavaConfig(Spring MVC 4.0)将JSON(杰克逊库)与我现有的应用程序一起使用
我有我的配置:
@Configuration
@EnableWebMvc
@ComponentScan({ "my.package.controller" })
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Bean(name = "viewResolver")
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
我想应用 JSON 配置,但没有找到解决方案。
我想我必须扩展WebMvcConfigurerAdapter。还有一个细节,我使用Spring Security。
你能帮我吗?
谢谢
试试这个:
@Bean
public ViewResolver contentNegotiatingViewResolver(
ContentNegotiationManager manager) {
List< ViewResolver > resolvers = new ArrayList< ViewResolver >();
InternalResourceViewResolver r1 = new InternalResourceViewResolver();
r1.setPrefix("/WEB-INF/pages/");
r1.setSuffix(".jsp");
r1.setViewClass(JstlView.class);
resolvers.add(r1);
JsonViewResolver r2 = new JsonViewResolver();
resolvers.add(r2);
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setViewResolvers(resolvers);
resolver.setContentNegotiationManager(manager);
return resolver;
}
要添加 Jackson 支持,应使用 MappingJacksonJsonView 或 MappingJackson2JsonView
public class JsonViewResolver implements ViewResolver {
public View resolveViewName(String viewName, Locale locale) throws Exception {
MappingJacksonJsonView view = new MappingJacksonJsonView();
view.setPrettyPrint(true);
return view;
}
}
在应用程序中.xml只是为了澄清我的例子有这个配置
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
因此可能需要在@Bean方法中将媒体类型添加到内容协商视图解析器中。
查看此内容以获取有关内容协商的更多信息