在使用XML方式配置项目,使用fastjson做为Json转换器时通常的在XML内添加如下的配置:
<mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json"/> <property name="features"> <array> <value>WriteMapNullValue</value> <value>WriteDateUseDateFormat</value> </array> </property> </bean> </mvc:message-converters>
当项目不使用XML配置而使用全注释方式时,实现WebMvcconfigurer接口并重写extendMessageConverters方法并添加fastjson转换器
@Configuration @EnableWebMvc @ComponentScan("com.wey.spring.controller") public class MvcConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/classes/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; } /** * 使用FastJson做为json转换器 */ public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); List<MediaType> mediaTypes = new ArrayList<MediaType>(); mediaTypes.add(new MediaType(MediaType.TEXT_HTML, Charset.forName("UTF-8"))); mediaTypes.add(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("UTF-8"))); mediaTypes.add(new MediaType(MediaType.APPLICATION_XML, Charset.forName("UTF-8"))); converter.setSupportedMediaTypes(mediaTypes); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); converter.setFastJsonConfig(fastJsonConfig); converters.add(converter); }
/**
* 静态资源
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:static/");
}
}