开发环境:myeclipse2015、tomcat8.0、jdk1.8
1、使用spring4.0.2.RELEASE、jackson1.9.13,pom.xml配置:
1 <properties> 2 <!-- <spring.version>4.0.2.RELEASE</spring.version> --> 3 <spring.version>4.1.1.RELEASE</spring.version> 4 <mybatis.version>3.2.6</mybatis.version> 5 <slf4j.version>1.7.7</slf4j.version> 6 <log4j.version>1.2.17</log4j.version> 7 <jackson.version>2.4.4</jackson.version> 8 </properties> 9 <dependencies> 10 <dependency> 11 <groupId>org.codehaus.jackson</groupId> 12 <artifactId>jackson-core-asl</artifactId> 13 <version>1.9.13</version> 14 </dependency> 15 <dependency> 16 <groupId>org.codehaus.jackson</groupId> 17 <artifactId>jackson-mapper-asl</artifactId> 18 <version>1.9.13</version> 19 </dependency> 20 </dependencies>
然后使用spring mvc的默认配置即可返回json,为了避免IE执行ajax时,返回json出现下载文件的问题,spring-mvc.xml可使用如下配置:
<!-- 避免IE执行ajax时,返回json出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> --> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- json转换器 --> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean>
2、使用spring4.1.1.RELEASE、jackson2.4.4
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency>
spring-mvc.xml配置:
<!-- 避免IE执行ajax时,返回json出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> --> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <!-- json转换器 --> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean>
其中:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter与spring4.0的配置不同,使用的MappingJackson2HttpMessageConverter。
有个问题需注意:如果在spring4.1.1下使用jackson2.4.0版本,启动tomcat后请求时,会报406错误: