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

spring restTemplate 支持返回近json和xml
servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-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/util
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">
       
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.spring.mvcrest.web" />
    <bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
          <property name="supportedMediaTypes" value="application/xml"/>
    </bean>
    <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
       <property name="supportedMediaTypes" value="application/json" />
    </bean>
    <bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
          <list>
            <value>com.spring.mvcrest.bean.Employee</value>
            <value>com.spring.mvcrest.bean.EmployeeList</value>
          </list>
        </property>
    </bean>
   
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
       <property name="messageConverters">
           <list>
               <ref bean="jsonConverter" />
               <ref bean="marshallingConverter" />
           </list>
       </property>
     </bean>

</beans>



RestClient.java

package com.spring.mvcrest.client;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import com.spring.mvcrest.util.CommonsUtil;

public class RestClient {
  
    private static final Stri