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.Result</value>  
  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。 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章