日期:2014-05-16  浏览次数:20268 次

Sping3 MVC JSON 例子

Sping3 MVC JSON 例子


1、引入下面两个jar包,我用的是1.8.10,好像1.4.2版本以上都可以,下载地址:http://wiki.fasterxml.com/JacksonDownload

jackson-core-asl-1.8.10.jar 

jackson-mapper-asl-1.8.10.jar

同时引入Sping 本身的jar包:

org.springframework.asm-3.1.1.RELEASE.jar
org.springframework.beans-3.1.1.RELEASE.jar
org.springframework.context-3.1.1.RELEASE.jar
org.springframework.core-3.1.1.RELEASE.jar
org.springframework.expression-3.1.1.RELEASE.jar
org.springframework.web-3.1.1.RELEASE.jar


2、Sping配置文件


web.xml

<servlet>
	<servlet-name>dispatchServlet</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/servlet-config.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>dispatchServlet</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

servlet-config.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:tx="http://www.springframework.org/schema/tx"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/mvc  
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
   
   <!-- 自动扫描bean,把作了注解的类转换为bean -->  
    <context:component-scan base-package="com.report.controller" />  
    
    <!-- 默认的注解映射的支持 -->  
    <mvc:annotation-driven/>
    <!-- 支持JSON数据格式 -->
    <bean  class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  
    <bean  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
    	<property name="messageConverters">
  			<list>
   				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
   					<property name="supportedMediaTypes">  
        				<list>  
            				<value>text/html;charset=UTF-8</value>  
        				</list>  
    				</property> 
   				</bean>
  			</list>
 		</property>
    </bean>
    
	<!--