簡體   English   中英

Spring MVC REST-根據請求內容類型返回xml或json

[英]Spring MVC REST - Returning xml or json according to request content type

我正在嘗試創建RESTful Web服務,它將根據請求的內容類型返回json或xml:

我的控制器如下所示:

@Controller
public class RESTController {

    @RequestMapping(value="/rest/{id}", method=RequestMethod.GET)
    @ResponseBody
    public User getUser(@PathVariable Long id){
        User user = .....
        return user;
    }

我的用戶類如下所示:

@XStreamAlias("user")
public class User {

    private long id;
    private String firstName;
    private String lastName; 
      other setters and getters..............
}

最后我的Servlet.xml如下所示:

<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.vanilla.rest.controllers" />

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="ignoreAcceptHeader" value="true" />
    <property name="favorPathExtension" value="false" />
    <property name="order" value="1" />
    <property name="mediaTypes">
        <map>
            <entry key="xml" value="application/xml" />
            <entry key="json" value="application/json" />
        </map>
    </property>
    <property name="defaultViews">
        <list>
            <ref bean="xmlView"/>
            <ref bean="jsonView"/>
        </list>
    </property>
</bean>

<bean id="jsonView"
      class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="contentType" value="application/json;charset=UTF-8"/>
    <property name="disableCaching" value="false"/>
</bean>

<bean id="xmlView"
      class="org.springframework.web.servlet.view.xml.MarshallingView">
    <property name="contentType" value="application/xml;charset=UTF-8"/>
    <constructor-arg>
        <ref bean="xstreamMarshaller"/>
    </constructor-arg>
</bean>

<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
    <property name="autodetectAnnotations" value="true" />
    <property name="annotatedClass" value="com.vanilla.rest.entities.User"/>
</bean>

我的問題是,無論我發送哪種內容類型,我總是會收到JSON響應。

在此處輸入圖片說明

看起來您需要添加

Accept: application/xml

到您的請求標頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM