spring mvc 同时输出json和xml

方式一: 
参考: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-xml-example/  
满足以下条件时会自动将对象转换为xml格式进行输出: 
引用
As i know, when Spring see 

1. Object annotated with JAXB 
2. JAXB library existed in classpath 
3. “mvc:annotation-driven” is enabled 
4. Return method annotated with @ResponseBody 

It will handle the conversion automatically.

方式二(建议使用,可以和json等方式同时开启): 
    
Xml代码   收藏代码
  1. <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  
  2.           <property name="mediaTypes">  
  3.                <map>  
  4.                     <entry key="xml" value="application/xml"/>  
  5.                     <entry key="json" value="application/json"/>  
  6.                map>  
  7.           property>  
  8.           <property name="defaultViews">  
  9.                <list>  
  10.                     <bean class="org.springframework.web.servlet.view.xml.MarshallingView">  
  11.                          <property name="marshaller">  
  12.                               <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">  
  13.                                    <property name="classesToBeBound">  
  14.                                         <list>  
  15.                                              <value>cn.flysnowxf.resp.Resultvalue>  
  16.                                         list>  
  17.                                    property>  
  18.                               bean>  
  19.                          property>  
  20.                     bean>  
  21.                     <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />  
  22.                list>  
  23.           property>  
  24.      bean>  
当请求accept=application/xml或者url以.xml结尾,将选择xml view进行处理,这里配置的xml解析器是Jaxb2Marshaller。 

你可能感兴趣的:(JAVA,WEB)