SpringMVC4.0以后版本返回json格式数据问题,有什么偏颇的地方希望大家多多斧正。在这个问题上困扰了我两天,这两天翻来覆去睡不着。一直在想这个问题。废话不多说下面进入正题。
1.创建创建web项目,加入SpringMVC的jar,我这里演示用spring-framework-4.2.3.RELEASE。jar包如下图所示:
2.配置web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
">
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="cn.xugang.."></context:component-scan>
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManagerFactoryBean"/>
<mvc:default-servlet-handler/>
<bean>
<property value="false"/>
<property value="false"/>
<property value="false"/>
<property>
<map>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
<entry key="xls" value="application/vnd.ms-excel"/>
</map>
</property>
</bean>
<bean>
<property>
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean>
<property>
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
<bean>
<property value="/WEB-INF/jsp/"></property>
<property value=".jsp"></property>
</bean>
</beans>
4.配置创建controller,使用@Responsebody注解,指定返回内容。