<mvc:annotation-driven/>初始化7个转换器
ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter
对于json的解析就是通过MappingJacksonHttpMessageConverter转换器完成的。
只添加<mvc:annotation-driven />还不行,需要在classpath环境中能找到Jackson包
Jackson包Maven配置
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
</dependency>
之前看资料有说过spring4.x之后就需要配置MappingJackson2HttpMessageConverter而不是默认的MappingJacksonHttpMessageConverter。而相应的jar包也需要使用对应的2.x版本
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
<!--注入的message-converters优先级高于默认注入的json转换器-->
</mvc:annotation-driven>
注意:默认情况下MappingJacksonHttpMessageConverter 会设置content为application/json,在IE9下返回会出现提示下载的现象,出现这种情况可以手动指定头信息为"text/html",或者"/"(所有,不确定就设置为这个)。
当只设置了"text/html"时,我试验的时候Ajax回调函数接收json值的时候不行,确实是传递过来了,但是也许是转换出了问题,所以在上面还加了个“application/json”就可以了。。。。。
当然也可以用fastjson,不过依赖的jar包就不一样了,而且配置消息处理器的方式也是需要自己添加的。