在Controller類中,需要返回JSON的方法上加上注釋@ResponseBody,這是必須的。
然后spring-servlet.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:p="http://www.springframework.org/schema/p" 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/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 啟動掃描所有的controller aokunsang--> <context:component-scan base-package="com.xxx"/> <!-- 定義注解驅動Controller方法處理適配器 ,注:該適配器必須聲明在<mvc:annotation-driven />之前,否則不能正常處理參數類型的轉換 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <!-- 設置全局返回JSON到前端時日期格式化 --> <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/> </bean> </property> </bean> </property> </bean> </list> </property> </bean> <!-- 會自動注冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter 兩個bean,是spring MVC為@Controllers分發請求所必須的。 並提供了:數據綁定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,讀寫XML的支持(JAXB),讀寫JSON的支持(Jackson) --> <mvc:annotation-driven /> <!-- 配置js,css等靜態文件直接映射到對應的文件夾,不被DispatcherServlet處理 --> <mvc:resources location="/resources/**" mapping="/resources/**"/> <!-- jsp頁面解析器,當Controller返回XXX字符串時,先通過攔截器,然后該類就會在/WEB-INF/views/目錄下,查找XXX.jsp文件--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>